Previous | Next | Trail Map | To 1.1 -- And Beyond! | GUI Changes: The AWT Grows Up


Writing an Action Listener

Action listeners are probably the easiest -- and most common -- event handlers to implement. You implement an action listener to respond to the user's indication that some implementation-dependent action should occur. For example, when the user clicks a button(in the Creating a User Interface trail), doubleclicks a list item(in the Creating a User Interface trail), chooses a menu item(in the Creating a User Interface trail), or presses return in a text field(in the Creating a User Interface trail), an action event occurs. The result is that an actionPerformed message is sent to all action listeners that are registered on the relevant component.

The ActionListener(in the API reference documentation) interface contains a single method, and thus has no corresponding adapter class. Here is the lone ActionListener method:

void actionPerformed(ActionEvent)
Notifies the listener that the user has indicated that an action should occur.

Here is the action event handling code from an applet named Beeper.java:

public class Beeper ...  implements ActionListener {
    ...
    //where initialization occurs:
        button.addActionListener(this);
    ...
    public void actionPerformed(ActionEvent e) {
	...//Make a beep sound...
    }
}
You can find examples of action listeners in the following sections:
A Simple Example
Contains and explains the applet whose code is shown above.
A More Complex Example
Contains and explains an applet that has two action sources and two action listeners, with one listener listening to both sources and the other listening to just one.
[Should probably talk about ActionEvent and link to its API doc.]


Previous | Next | Trail Map | To 1.1 -- And Beyond! | GUI Changes: The AWT Grows Up