| 
 | 
Writing Event Listeners | 
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.When the user clicks a button
, chooses a menu item
or presses Return in a text field
, an action event occurs. The result is that an
actionPerformedmessage is sent to all action listeners that are registered on the relevant component.Action Event Methods
TheActionListenerinterface contains a single method, and thus has no corresponding adapter class. Here is the lone
ActionListenermethod:
void actionPerformed(ActionEvent)- Called 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 namedBeeper:Thepublic class Beeper ... implements ActionListener { ... //where initialization occurs: button.addActionListener(this); ... public void actionPerformed(ActionEvent e) { Toolkit.getDefaultToolkit().beep(); } }Beeperapplet is described in this trail's introduction to events, Some Simple Event-Handling Examples. You can find the entire program inBeeper.java. The other example described int that section,MultiListener.java, has two action sources and two action listeners, with one listener listening to both sources and the other listening to just one.Here are some more of the many source files in this tutorial that contain action listeners:
The ActionEvent Class
TheactionPerformedmethod has a single parameter: anActionEventobject. The
ActionEventclass defines two useful methods:Also useful is the
String getActionCommand()- Returns the string associated with this action. Most objects that can generate actions support a method called
 setActionCommandthat lets you set this string. If you don't set the action command explicitly, then it's generally the text displayed in the component. For objects with multiple items, and thus multiple possible actions, the action command is generally the name of the selected item.int getModifiers()- Returns an integer representing the modifier keys the user was pressing when the action event occurred. You can use the
 ActionEvent-defined constantsSHIFT_MASK,CTRL_MASK,META_MASK, andALT_MASKto determine which keys were pressed. For example, if the user Shift-selects a menu item, then the following expression is nonzero:actionEvent.getModifiers() & ActionEvent.SHIFT_MASKgetSourcemethod, whichActionEventinherits fromEventObjectby way of
AWTEvent. See The AWTEvent Class.
| 
 | 
Writing Event Listeners |