|
||
|
|
|
|
|
Events
When triggered, a Component can either respond to the event itself or 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. Note: This applies to the Event model in the JDK 1.0.2. The JDK 1.1 will be backwards compatible, but the Event model will be different. We 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, // we obtain it via getGraphics() method. getGraphics().drawString("hi", x, y); return true; // say that we handled this event } } Because Container objects such as Panel and Applet are also subclasses of Component, they too may respond to events. We have trapped the mouseDown event in the Applet subclass simply by overriding method mouseDown. Had we not overridden this method, Component.mouseDown would have been 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 that 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 the arg field of that Event. For a Button, the argument is the String label of that Button. In Action Events we chronicle the event arguments for the various components. This section includes the following subsections: |