Given by Nancy McCracken at CPS616 spring 1997 on Jan 29 1997. Foils prepared 1 February 97
Abstract * Foil Index for this file
Secs 44.6
See also color IMAGE
Exceptions in some detail |
Brief Introduction to Threads (as used in graphics) |
Graphics including Image Drawing and Downloading
|
Abstract Window Toolkit (Started)
|
This table of Contents
Abstract
Instructor: Nancy McCracken |
teamed with Meryem Ispirli, Geoffrey Fox, |
Tom Scavo, John Yip |
Syracuse University |
111 College Place |
Syracuse |
New York 13244-4100 |
Exceptions in some detail |
Brief Introduction to Threads (as used in graphics) |
Graphics including Image Drawing and Downloading
|
Abstract Window Toolkit (Started)
|
The language itself supports concept of an exception |
Java supports a hierarchical model of exceptions which allow and indeed require user to supply suitable handlers for any exception that can occur in a Java program |
Note exceptions that can occur in a method must either be caught (i.e. handled inside method) or thrown (i.e. returned to callee) |
Thrown exceptions are like returned arguments and are for instance part of interface to a method |
Exceptions are all (at some level in hierarchy) subclasses of Throwable class |
method1 {
|
} |
method2 throws Exception3 {
|
} |
method3 throws Exception3 {
|
} |
As Examples of hierarchy: |
catch(InvalidIndexException e) {..} would catch particular exception whereas |
catch(ArrayException e) {..} would catch all Arrayexceptions |
File file; /* defines file to be object of class File */ |
try{
|
} catch (IOException e) {
|
return; |
} |
/* but the optional finally clause will be executed
|
finally {
|
} |
There are two subclasses of Throwable
|
Exception has a subclass RuntimeException that need NOT be caught |
Typical RuntimeException subclasses are |
ArithmeticException ClassCastException IndexOutofBoundException |
When writing a Java applet, your code is overriding one of the standard applet methods, and you are not allowed to throw any exceptions that it would not. So, in general, you must handle exceptions. |
What to do: The standard trick of writing a message to System.out works fine for debugging when running with the applet viewer. It also works fine with the Netscape browser for errors that you don't really expect to happen in working code (like your code had a null pointer) because Netscape provides a "Java console" under the Options menu that displays all messages. |
However, for errors that you really want to bring to the attention of the user, such as they typed in their URL incorrectly and the network methods returned a "malformedURLException", you can put up a pop-up window in the style of professional GUI programs. |
Note that you don't have to micromanage exceptions - you don't have to put a "try-catch" construct around every statement that can throw an exception. You can put the "try-catch" around the entire code with the same catch action or even put different catches for different actions of the errors. |
Instructors: Geoffrey Fox , |
Nancy McCracken |
Syracuse University |
111 College Place |
Syracuse |
New York 13244-4100 |
A thread is a single sequential flow of control within a process. |
If a process has more than one thread, then each thread executes concurrently. |
Any Java applet which has extensive execution or loops to repaint the window must run as a concurrent thread with the browser window. |
To make an applet with a thread, which is almost always recommended:
|
These start and stop methods can always be used |
The body of the applet is in the run method, in this case a loop to keep showing the date. |
Most applets and windows applications want to change what is drawn on the screen over its lifetime. This can be a sequenced animation, response to user input or mouse events, and so on. |
Whenever you want to redraw the screen, call
|
Repaint gets the graphics context and creates a thread to call update, which calls your paint function. So all your drawing changes are also put into paint. |
One draws a sequence of text and shapes to define the screen, where the position of the object in the screen is given by pixel coordinates. If one object overlaps another, the latest one drawn covers up the area of overlap.
|
Graphicsinstance.setFont(particularFont) will set the current Font in the instance Graphicsinstance of graphics class to the value particularFont of class Font. There are several other such Font related methods in the Graphics class |
The class Font has an important constructor used as in |
Font particularFont = new Font("TimesRoman",Font.PLAIN,36); |
where one can use Courier Helvetica etc. instead of Time Roman |
Font.PLAIN, Font.BOLD, Font.ITALIC are possible text styles |
FontMetrics fm = getFontMetrics(particularFont); // allows one to find out about the font, such as leading, aspect, etc. |
fm.stringWidth("text"); // returns pixel width of string "text" |
fm.getHeight(); // returns total height of one line of Font |
Some of These are in Applet and some in parent (in particular Component) |
public void init() is called ONCE and ONCE only when the applet is loaded or reloaded. Set initial parameters etc. here. |
public void destroy() is what you do when Applet is entirely finished and you need to clean up stray threads or connections to be closed. |
public void start() is called whenever the applet is started which can happen several times during an applet's life-cycle as it starts each time you revisit a page |
public void stop() is called when we temporarily leave Applet to visit another page. A wise move would be to suspend running of Threads to save system resources. |
public void paint(Graphics g) actually has an argument and draws what you want on the screen |
There is somewhat confusing other methods update() and repaint() which need to used in advanced applications. You may need to call repaint() in a dynamic applet to change display but update() would not need to be called as invoked by repaint(). However update() is sometimes best overridden |
public void repaint() is a request by you to the Java runtime to update screen |
public void update(Graphics g) is invoked by repaint() and performs the screen update which involves clearing screen and invoking paint() |
The Applet class provides a method getImage, which retrieves an image from a web server and creates an instance of the Image class. |
Image img = getImage(new URL("http://www.tc.com/image.gif")); |
Another form of getImage retrieves the image file relative to the directory of the HTML or the directory of the java code. |
Image img = getImage(getDocumentBase(), "images/image.gif"); |
Image img = getImage(getCodeBase(), "images/image.gif"); |
The Graphics class provides a method drawImage to actually display the image on the browser screen. |
You can also scale the image to a particular width and height. |
When drawImage is called, it draws only the pixels of the image that are already available. |
Then it creates a thread for the imageObserver. Whenever more of the image becomes available, it activates the method imageUpdate, which in turn which call paint and drawImage, so that more of the image should show on the screen. |
The default imageUpdate doesn't work if you are double buffering the window in which the image appears. |
More control over showing the image as it downloads can be obtained by working with the imageObserver class and the new MediaTracker class, using methods which can tell you when the image has fully arrived. |
This example shows how to get the actual height and width of the image to use in scaling the image under java program control. |
Unless you are careful, dynamic applets will give flickering screens |
This is due to cycle |
paint(g) |
update(g) clearing screen |
paint(g) drawing new screen ..... |
where flicker caused by rapid clear-paint cycle. |
There are two ways to solve this problem which involve changing update in different ways
|
This sets background color and initializes applet bounding rectangle to this color
|
getBackground() and getForeground() are methods in component class |
fillRect() is a method in Graphics class |
Here you have two "graphics contexts" (frame buffers of the size of the applet), and you construct the next image for an animation "off-line" in the second frame buffer. |
This frame buffer is then directly copied to the main applet Graphics object without clearing image as in default update() |
In init(), you would create the frame buffer:
|
In paint(), one will construct applet image in offscreenGraphics as opposed to the argument g of paint(). So one would see statements such as:
|
Finally at end of paint(), one could transfer the off-screen image to g by
|
One would also need to override the update() method by |
public void update(Graphics g) {
|
This technique is most effective in eliminating flicker, but does take longer and use more memory. |
Events ( distinguish these from Exceptions!) are the way the AWT interacts with the user at mouse or keyboard. |
The AWT calls particular event handlers (analogous to exception or interrupt handlers) when user interacts with system in particular ways. |
The handling is defined in packages java.awt and java.awt.peer (the machine dependent stuff) with method handleEvent() in class Component(peer) |
One could add additional capability here for systems with nifty virtual reality and other user interfaces but we won't cover this here! |
The Event class has various special class (static) variables defined including
|
The Component class (grandparent of Applet) has a rich set of Event handlers which you should override if you wish to process particular input |
public boolean mouseDown(Event evt, int x, int y) {
|
Other handlers are mouseDrag, mouseEnter (enters current component), mouseExit, mouseMove (with its button up), keyUp, keyDown |
We set up a test program that creates 3 movable objects, a rectangle, circle and triangle, as in the earlier example. In this program, we start with them all red. Whenever the mouse is detected to be over one of the objects, its color is changed to cyan. If the mouse button is used to drag the object, we move the object to the mouse location. |
Note that it is not necessary to introduce a thread for this applet since it is not running continuously - it is mostly waiting for mouse events. |
In this example, update does all the drawing. It also sets a background color rectangle with a 1 pixel border in the foreground color. |
Whenever the user moves the mouse, a message is sent from the client workstation to the Java system. It generates a form of interrupt called an event. Your Java applet can choose to provide a method which does appropriate response for any event. This is called an event handler - you must return true to show the general event handler that you have intervened. |
These handle the sequence of: the user clicks the mouse (mouse down), moves the mouse (mouse drag) and releases the mouse button (mouse up). |
We add methods to detect when the mouse is inside an object, and a more general method moveTo for large moves under dragging. |
You may also choose to respond to individual keys being pressed from the keyboard. (Later we will learn of a more general way to handle text input.) |