GUI Changes: The AWT Grows Up |
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, doubleclicks a list item, chooses a menu item, or presses return in a text field, an action event occurs. The result is that anactionPerformed
message is sent to all action listeners that are registered on the relevant component.Action Event Methods
TheActionListener
interface contains a single method, and thus has no corresponding adapter class. Here is the loneActionListener
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 namedBeeper.java
:You can find examples of action listeners in the following sections:public class Beeper ... implements ActionListener { ... //where initialization occurs: button.addActionListener(this); ... public void actionPerformed(ActionEvent e) { ...//Make a beep sound... } }
- 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
ClassTheactionPerformed
method has a single parameter: anActionEvent
object. TheActionEvent
class defines two useful methods:Also useful is the
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
, andActionEvent.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_MASKgetSource
method, which returns the object (a component or menu component) that generated the action event. ThegetSource
method is defined in one ofActionEvent's
superclasses,EventObject
.
GUI Changes: The AWT Grows Up |