Events

Once an applet has constructed a graphical interface, it waits for an event such as a mouse click or a Button press to trigger an action. All Component objects except Label can be triggered into action by an event. An event is sent to a component by calling its handleEvent method with an Event object as an argument, which contains information about the activated object and the type of event. Method handleEvent, in turn, interprets the type of event and calls one of several "convenience" methods such as mouseDown and keyDown. Consequently, to have a Component respond to an event, all you have to do is override the right method in the appropriate subclass of Component.

When triggered, a Component can either respond to the event itself or instead let the event be handled by the enclosing Container object. If the enclosing Container does not handle the event, its enclosing Container is sent the event until the top of the containment hierarchy is reached or a Component handles the event. Components indicate that they have handled an event by returning true from handleEvent or from one of the convenience methods. Returning false causes the event to move up a level in the containment hierarchy. The path of Component objects taken by an event is called the event chain.

It is useful to begin with a simple example of how an applet responds to a mouse event. Consider the following applet that prints "hi" everywhere you click the mouse:



Corresponding source code:

import java.awt.*;
import java.applet.Applet;

public class SimpleEvent extends Applet {
    public boolean mouseDown(Event e,int x,int y) {
        // upon mouse click, put "hi" at that location
        // since graphics context is not passed in,
        // obtain it via getGraphics() method.
        getGraphics().drawString("hi", x, y);
        return true; // say that event handled
    }
}

Because Container objects such as Panel and Applet are also subclasses of Component, they too may respond to events. You can trap the mouseDown event in the Applet subclass simply by overriding method mouseDown. If you do not override this method, Component.mouseDown would be called, which does nothing but return false indicating that it did not handle the event. There are a number of other events that you may want to handle in your applet. See Event Convenience Methods.

Clicking the mouse over a non-Container Component does not normally generate a mouseDown event in the current JDK implementation. A mouse click normally activates a Component, which triggers a call to method action. For example, pushing a Button invokes method action up the event chain until some object handles the event (returns true). The action method is passed the Event object as well as arg field of that Event. For a Button, the argument is the String label of that Button. In Action Events the event arguments are chronicled for the various components.

This section has the following subsections: