|
|
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 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 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
ActionEventClassTheactionPerformedmethod has a single parameter: anActionEventobject. The
ActionEventclass 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_MASKto 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_MASKgetSourcemethod, which returns the object (a component or menu component) that generated the action event. ThegetSourcemethod is defined in one ofActionEvent'ssuperclasses,EventObject.
|
|
GUI Changes: The AWT Grows Up |