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

Methods for Drawing and Event Handling

The Simple applet defines its onscreen appearance by overriding the paint method:
class Simple extends Applet {
    . . .
    public void paint(Graphics g) { . . . }
    . . .
}

The paint method is one of two display methods an applet can override:

paint
The basic display method. Many applets implement the paint method to draw the applet's representation within a browser page.
update
A method you can use along with paint to improve 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.

Applets inherit a group of event-handling methods from the Component class. (The architecture of the AWT event system is discussed on the Events(in the Creating a User Interface trail) page.) The Component class defines several methods, such as action and mouseDown, for handling particular types of events, and then one catch-all method called handleEvent.

To react to an event, an applet must override either the appropriate event-specific method or the handleEvent method. For example, adding the following code to the Simple applet makes it respond to mouse clicks.

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


You can't run applets. Here's what you'd see if you could:


Note: Because some old browsers don't support 1.1, the above applet is a 1.0 version (here is the 1.0 code; here's the 1.1 code). To run the 1.1 version of the applet, go to example-1dot1/SimpleClick.html. For more information about running applets, refer to About Our Examples.


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