Input/Output
- InputStream and OutputStream are abstract classes.
- FileInputStream and FilterInputStream both inherit directly from InputStream.
- FileOutputStream and FilterOutputStream both inherit directly from OutputStream.
- DataInputStream inherits directly from FilterInputStream.
- DataOutputStream inherits directly from FilterOutputStream.
- When you create a Filter stream, you must specify the stream to which it will attach.
- A Filter stream processes a stream of bytes in some way. By "chaining" any number of Filter streams, you can add any amount of processing to a stream of bytes.
- DataInputStream, DataOutputStream and RandomAccessFile know how to work with Java data types because they implement the DataInput and DataOutput interfaces, whereas FileInputStream and FileOutputStream know only how to work with individual bytes.
- RandomAccessFile implements both DataInput and DataOutput methods - RandomAccessFile objects can read from and write to files.
- The File class is not used to create files. Can create a file using an instance of class RandomAccessFile and FileOutputStream.
- To test if a File object refers to an existing file, you can invoke exists() which returns true or false. The File methods canRead() and canWrite() return boolean values that indicate whether the application can read from or write to the file. (Note: applets can’t write to a file.)
- Can use File methods to make a permanent change to the file system. For example, you can call delete() or rename(). For rename(), need to supply a File object which embodies the new name.
- You can create a directory using the File class. The method mkdir() does this.
- It is possible to navigate the filing system using the File class. Methods getParent(), getPath() and getName() are provided, and also getAbsolutePath().
- The method getAbsolutePath() returns the name of the current user directory (the full pathname included) with the file name concatenated. See Practice Exam 1 Q.45
- Creating a FileOutputStream object creates the appropriate file. If the file already exists, FileOutputStream replaces it (unless the FileOutputStream object is created using the constructor which takes a String and a boolean - see later)
- Upon creation of a RandomAccessFile object, need to supply a file object plus a mode. Alternatively, can supply a filename plus a mode.
- Valid modes for RandomAccessFile are "r" and "rw".
- Constructors for FileInputStream: one takes a String, one takes a File, one takes a FileDescriptor
- Constructors for FileOutputStream: one takes a String, one takes a File, one takes a FileDescriptor, one takes a String and a boolean (which indicates whether or not to append).
- Constructors for FilterInputStream: one only, which takes an InputStream
- Constructors for FilterOutputStream: one only, which takes an OutputStream
- See Chapter 11 Review Questions for io stuff - very useful.
Threads
- A Java program runs until the only threads left running are daemon threads.
- A Thread can be set as a user or daemon thread when it is created.
- In a standalone program, your class runs until your main() method exists - unless your main() method creates more threads.
- You can initiate your own thread of execution by creating a Thread object, invoking its start() method, and providing the behaviour that tells the thread what to do. The thread will run until its run() method exists, after which it will come to a halt - thus ending its life cycle.
- The Thread class, by default, doesn’t provide any behaviour for run().
- There are two ways to provide the behaviour for a thread
- Subclass the thread and override the run() method - see p.253 of Exam Guide.
- Implement the Runnable interface and indicate an instance of this class will be the thread’s target.
- A thread has a life cycle. Creating a new Thread instance puts the thread into the "new thread" state. When the start() method is invoked, the thread is then "alive" and "runnable". A thread at this point will repond to the method isAlive() by returning true.
- The thread will continue to return true to isAlive() until it is "dead", no matter whether it is "runnable" or "not runnable".
- If 2 threads are alive, with the same highest priority, the JVM switches between them. The JVM will switch between any number of threads with the same highest priority.
- The priority numbers for threads falls between the range of Thread.MIN_PRIORITY and Thread.MAX_PRIORITY.
- The default thread priority is Thread.NORM_PRIORITY.
- New threads take on the priority of the thread that spawned them.
- You can explicitly set the priority of a thread using setPriority(), and you can get the priority of a thread using getPriority(). There is no constructor for thread which takes a priority.
- The JVM determines the priority of when a thread can run based on its priority ranking, but this doesn’t mean that a low priority thread will not run.
- The currently executing thread can yield control by invoking yield(). If you invoke yield(), Java will pick a new thread to run. However, it is possible the thread that just yielded might run again immediately if it is the highest priority thread.
- There are 3 types of code that can be synchronized: class methods, instance methods, any block of code within a method.
- Variables cannot take the synchronized keyword.
- Synchronization stays in effect if you enter a synchronized method and call out to a non-synchronized method. The thread only gives up the monitor after the synchronized method returns.
- Using a thread’s stop() method will make it die.
- There are 3 ways to transition a thread between "runnable" and "not runnable"
put it to sleep and wake it up (not on the test) pause it and resume it (not on the test) use the methods wait(), notify() and notifyAll()
- these are methods of class Object. wait() throws InterruptedException. - The third method listed above allows communication between the threads, whereas the other 2 methods don’t.
- By using the methods wait(), notify() and notifyAll(), any thread can wait for some condition in an object to change, and any thread can notify all threads waiting on that object’s condition that the condition has changed and that they should continue.
- When a waiting thread pauses, it relinquishes the object’s monitor and waits to be notified that it should try to reacquire it.
- If you know you only have one thread waiting on a condition, you can feel free to use notify(), otherwise you should use notifyAll(). The notifyAll() method wakes up all threads waiting to reacquire the monitor for the object.
- The reasons why a thread might be "alive" and "not runnable" are as follows:
- the thread is not the highest priority thread and so is not able to get CPU time
- the thread has been put to sleep using the sleep() method (of class Thread. Throws InterruptedException)
- the thread has been suspended using the suspend() method
- the thread is waiting on a condition because someone invoked wait() for the thread
- the thread has explicitly yielded control by invoking yield()
Graphical User Interfaces
- If you want to explicitly repaint a component, you should not call paint() directly. Instead you should invoke your component’s repaint() method.
- The repaint() method is overloaded. The no-args version of repaint() does not cause your user interface to repaint right away. In fact, when repaint() returns, your component has not yet been repainted - you’ve only issued a request for a repaint(). There is another version of repaint() that requests the component to be repainted within a certain number of milliseconds.
- The repaint() method will cause AWT to invoke a component’s update() method. AWT passes a Graphics object to update() - the same one that it passes to paint(). So, repaint() calls update() which calls paint().
- The Graphics object that AWT hands to update() and paint() is different every time the Component is repainted.
- When Java repaints on its own, such as when the user resizes an applet, the AWT does not invoke update() - it just calls paint() directly.
- The update() method does three things in this order:
- clears the background of the object by filling it with its background colour
- sets the current drawing colour to be its foreground colour
- invokes paint(), passing it the Graphics object received
- Common graphics methods:
- drawString() - takes a String, followed by x then y co-ord of baseline for first char
- drawLine() - takes x then y co-ords of starting point, then x then y co-ords of end point
- drawRect() / fillRect() - take 4 params - x then y co-ords of top left corner, then width then height
- drawOval() / fillOval() - take 4 params - x, y, width, height and draw an oval inside corresponding rectangle
- drawPolygon() / fillPolygon() - (int[] xpoints, int[] ypoints, int npoints) - array of x co-ords then array of y co-ords followed by the number of points to use
- drawArc() / fillArc() - takes 6 params - x then y co-ord of top left corner (of bounding rectangle of corresponding oval), width then height of arc, then start angle (not really an angle, more a position on the clock - 0 represents 3 o’clock), then number of degrees to move along the arc. Last parameter can also be negative, if you want to move in a clockwise direction round the arc.
- The Image class does not provide a constructor for specifying where an image will come from.
- You can obtain an Image, typically by downloading it from the Internet by specifying a URL. You can retrieve an image and obtain an Image object by invoking an Applet method named getImage(). This method takes a URL.
- When the getImage() method returns, the data for the image is not necessarily immediately available. The method returns right away, even if the image resource is located over the Internet on a Web server and must be downloaded.
- When you invoke the Graphics method drawImage() the image download begins. The object you specify as an ImageObserver keeps the Java graphics system up-to-date on the state of the download. When the ImageObserver sees that the download is complete, it notifies the graphics system that it can draw the image in its entirety.
- ImageObserver is an interface. The Component class implements this interface, so any component (such as an Applet itself) can be used as an ImageObserver.
- TextArea takes rows then cols in constructor. If you type in more text than can be displayed all at one, scrollbars appear automatically.
- TextField takes only cols. A user may one type one line into a TextField. No scrollbars appear if the line is too long to be displayed, but can use arrow keys to move to beginning or end of text.
- TextArea and TextField both inherit from TextComponent which provides a setEditable() method.
- For a variable width font, TextArea / TextField width is based on average of letter widths.
- Can populate a List using addItem() method.
- As well as a no-args constructor and a constructor which takes number of rows, List class also has a constructor which takes number of rows followed by a boolean value which represents whether or not multiple list item selections are allowed.
-
- Java 1.0
- Component methods for Java 1.0.2 - enable(), disable(), show(), hide(), size(), resize(), setForeground(), setBackground().
- enable() / disable() - make a component selectable or not by the user.
- size() / resize() - the size() method retrieves the size of the Component as a Dimension object which has two fields (width and height). The resize() method sets the size of the Component. The method is overloaded - one version takes a Dimension object and the other takes width and height directly as int values.
- show() / hide() - the show() method makes a Component visible, the hide() method makes a Component invisible. The show() method is overloaded so that you can supply a boolean parameter to indicate whether to show the Component (if the parameter is true).
- A Frame is only visible when the show() method has been invoked.
- Component methods for Java 1.1 - setEnabled(), getSize(), setSize(), setVisible(), setForeground(), setBackground(). setEnabled() replaces enable() / disable() and takes a boolean value. getSize() and setSize() replace size() / resize(). setVisible() replaces show() / hide() and takes a boolean value.
- Java 1.0
- Java provides a Color class which defines many static constants that contain instances of class Color already initialized to common colours. To use red, for example, you can access Color.red. The Color class has a constructor which takes three int values of red, green and blue so that you can make up your own colour.
- Each container has exactly one layout manager which determines how to arrange the Components within a Container.
- A layout manager is any class that implements the LayoutManager interface. Java’s 5 layout managers all inherit directly from class Object, but they implement the LayoutManager interface, which defines 5 abstract methods:
- addLayoutComponent()
- layoutContainer()
- minimumLayoutSize()
- preferredLayoutSize()
- removeLayoutComponent()
- Instead of invoking the layout manager’s methods yourself, Java’s default Container methods invoke them for you at the appropriate times. These Container methods include add(), getMinimumSize(), getPreferredSize(), remove() and removeAll() (these are all Java 1.1 methods).
- Each type of container comes with a default layout manager. Default for a Frame, Window or Dialog is BorderLayout. Default for a Panel is FlowLayout().
- A FlowLayout object arranges components left to right and top to bottom, centering each line as it goes. The FlowLayout layout manager is the only layout manager which allows components to be their preferred size. If a container using a FlowLayout is resized, all of the components inside it might need to be rearranged, and some might not be completely visible.
- A BorderLayout object arranges components according to the directions "North", "South", "East" and "West". There’s also an area for "Center" which includes any space left over from other regions.
- Components are rarely allowed to be their preferred size in a BorderLayout. BorderLayout stretches components. Stretches "North" and "South" components horizontally. Stretches "East" and "West" components vertically. Stretches "Center" components both horizontally and vertically.
- If nothing is placed in "East" or "West", for example, then the "Center" stretches all the way from the left edge of the Container to the right edge.
- Some components are stretchable and others are not. For example, Button, Label and TextField are stretchable, whereas Checkbox is not.
- GridLayout objects allow you to specify a rectangular grid in which to place the components. Each cell in the grid is the same height as the other cells, and each width is the same as the other cells. Components are stretched both horizontally and vertically to fill the cell.
- When a GridLayout object is first constructed, you must first specify how many rows and how many columns the grid will have. Components are added to the grid left to right and top to bottom. If more components are added than there are columns, the GridLayout keeps the same number of rows but adds the necessary number of columns.
- You can change a Container’s layout manager to be a different one by invoking setLayout().
No comments:
Post a Comment