Under Java 1.0, every Component class defined an action method that captured all events fired by its Component subclasses. This meant that every event fired by every Component class was handled by an action method. In Chapter 4, for example, the GATest applet declared an action function to process events generated by the Go button.
public boolean action(Event event, Object obj)
{
if (event.target == ctlGo)
{
// Do whatever the Go button is supposed to do
}
}
When the add method adds a child Component class to a parent, the parent automatically receives notification of all child events via its action method, even if the parent has no interest in those events.
In the delegation event model introduced in Java 1.1, an event is linked to a set of listener objects; only those objects that declare their interest in an event will be notified when the event fires. Under the delegation model, GATest would declare itself as a listener to specific “action” events by implementing the ActionListener interface. For instance, the applet would be a listener to ctlGo’s events if it included code such as the following.
// Create controls
ctlGo = new Button("Go");
add(ctlGo);
ctlGo.addActionListener(this);
The ActionListener interface declares a method named actionPerformed, which has a single parameter of type ActionEvent. Notice how the similarity in naming links the ActionEvent parameter to an ActionListener and to the actionPerformed method; this convention is followed for all predefined event types. The following code shows how actionPerformed would be implemented in SATest.
public void actionPerformed(ActionEvent event)
{
// Do whatever the Go button is supposed to do
}
The actionPerformed method will “hear” all events fired by objects that GATest listens to; in this case, GATest registers itself as a listener only for ctlGo events. The actionPerformed method can safely assume that it will be invoked only when the user clicks the Go button.
Note A powerful technique is to define inner classes as listeners to events from different Component classes. For example, if your class contains a pair of buttons, Stop and Go, you can define two inner class objects (such as HandleStop and HandleGo) to encapsulate event handling for each button.