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.

Action Event Methods

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)
Called by the AWT just after the user informs the listened-to component that an action should occur.

Examples of Handling Action Events

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.

The ActionEvent Class

The actionPerformed method has a single parameter: an ActionEvent(in the API reference documentation) object. The ActionEvent class defines two useful methods:
getActionCommand
Returns the string associated with this action. Generally, this is a label on the component -- or on the selected item within the component -- that generated the action.
getModifiers
Returns an integer representing the modifier keys the user was pressing when the action event occurred. You can use the constants ActionEvent.SHIFT_MASK, ActionEvent.CTRL_MASK, ActionEvent.META_MASK, and ActionEvent.ALT_MASK to determine which key was pressed. For example, if the user Shift-selects a menu item, then the following expression is nonzero:
    actionEvent.getModifiers() & ActionEvent.SHIFT_MASK
    
Also useful is the getSource method, which returns the object (a component or menu component) that generated the action event. The getSource method is defined in one of ActionEvent's superclasses, EventObject(in the API reference documentation).


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