Previous | Next | Trail Map | Writing Applets | Overview of Applets


Methods for Drawing and Event Handling

class Simple extends Applet {
    . . .
    public void paint(Graphics g) { . . . }
    . . .
}
The Simple applet defines its onscreen appearance by overriding the paint() method. The paint() method is one of two display methods that applets can override:
paint()
the basic display method; most applets implement this method to draw the applet's representation within a browser page
update()
a method you can use along with paint() to make improvements in drawing performance
Applets inherit their paint() and update() methods from the Applet class, which inherits them from the Abstract Window Toolkit (AWT) Component class. For an overview of the Component class, and the AWT in general, see the Overview of the Java UI(in the Creating a User Interface trail) lesson. Within the overview, the architecture of the AWT drawing system is discussed on the Drawing(in the Creating a User Interface trail) page.

From the Component class, applets inherit a group of methods for event handling. (Within the overview, the architecture of the AWT event system is discussed on the Events(in the Creating a User Interface trail) page.) The main event-handling method -- the one that's called (by default) whenever any event occurs -- is handleEvent(). The Component class also defines some convenience methods for handling certain kinds of events: mouseEnter(), mouseExit(), mouseMove(), mouseUp(), mouseDown(), mouseDrag(), keyDown(), and action().

To react to an event, an applet must override either handleEvent() or the convenience method corresponding to the event. For example, adding the following code to the Simple applet makes it respond to mouse clicks.

public boolean mouseDown(java.awt.Event evt, int x, int y) {
    addItem("click!... ");
    return false;
}
Below is the resulting applet. When you click within its rectangle, it displays the word "click!...".


Previous | Next | Trail Map | Writing Applets | Overview of Applets