How to Write an Action Listener
Action listeners are probably the easiest — and most common — event handlers to implement. You implement an action listener to define what should be done when an user performs certain operation.
An action event occurs, whenever an action is performed by the user. Examples: When the user clicks a button, chooses a menu item, presses Enter in a text field. The result is that an actionPerformed message is sent to all action listeners that are registered on the relevant component.
To write an Action Listener, follow the steps given below:
- Declare an event handler class and specify that the class either implements an ActionListener interface or extends a class that implements an ActionListener interface. For example:
public class MyClass implements ActionListenersomeComponent.addActionListener(instanceOfMyClass);public void actionPerformed(ActionEvent e) < . //code that reacts to the action. >In general, to detect when the user clicks an onscreen button (or does the keyboard equivalent), a program must have an object that implements the ActionListener interface. The program must register this object as an action listener on the button (the event source), using the addActionListener method. When the user clicks the onscreen button, the button fires an action event. This results in the invocation of the action listener's actionPerformed method (the only method in the ActionListener interface). The single argument to the method is an ActionEvent object that gives information about the event and its source.
Let us write a simple program which displays how many number of times a button is clicked by the user. First, here is the code that sets up the TextField , button and numClicks variable:
public class AL extends Frame implements WindowListener,ActionListener < TextField text = new TextField(20); Button b; private int numClicks = 0;In the above example, the event handler class is AL which implements ActionListener.
We would like to handle the button-click event, so we add an action listener to the button b as below:
b = new Button("Click me"); b.addActionListener(this);In the above code, Button b is a component upon which an instance of event handler class AL is registered.
Now, we want to display the text as to how many number of times a user clicked button. We can do this by writing the code as below:
public void actionPerformed(ActionEvent e) < numClicks++; text.setText("Button Clicked " + numClicks + " times");Now, when the user clicks the Button b, the button fires an action event which invokes the action listener's actionPerformed method. Each time the user presses the button, numClicks variable is appended and the message is displayed in the text field.
Here is the complete program(AL.java):
import java.awt.*; import java.awt.event.*; public class AL extends Frame implements WindowListener,ActionListener < TextField text = new TextField(20); Button b; private int numClicks = 0; public static void main(String[] args) < AL myWindow = new AL("My first window"); myWindow.setSize(350,100); myWindow.setVisible(true); >public AL(String title) < super(title); setLayout(new FlowLayout()); addWindowListener(this); b = new Button("Click me"); add(b); add(text); b.addActionListener(this); >public void actionPerformed(ActionEvent e) < numClicks++; text.setText("Button Clicked " + numClicks + " times"); >public void windowClosing(WindowEvent e) < dispose(); System.exit(0); >public void windowOpened(WindowEvent e) <> public void windowActivated(WindowEvent e) <> public void windowIconified(WindowEvent e) <> public void windowDeiconified(WindowEvent e) <> public void windowDeactivated(WindowEvent e) <> public void windowClosed(WindowEvent e) <> >More Examples: Beeper program example is available in this trail's introduction to events, Introduction to Event Listeners. You can find the entire program in Beeper.java . The other example described in 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.
The Action Listener API
Because ActionListener has only one method, it has no corresponding adapter class.
Method | Purpose |
---|---|
actionPerformed(actionEvent) | Called just after the user performs an action. |
actionEvent.getModifiers() & ActionEvent.SHIFT_MASK
Examples that Use Action Listeners
The following table lists some of the many examples that use action listeners.
Example | Where Described | Notes |
---|---|---|
Beeper | This section and Introduction to Event Listeners | Contains one button with one action listener that beeps when you click the button. |
MultiListener | Introduction to Event Listeners | Registers two different action listeners on one button. Also registers the same action listener on two different buttons. |
RadioButtonDemo | How to Use Radio Buttons | Registers the same action listener on five radio buttons. The listener uses the getActionCommand method to determine which radio button fired the event. |
MenuDemo | How to Use Menus | Shows how to listen for action events on menu items. |
TextDemo | How to Use Text Fields | An applet that registers an action listener on a text field. |
IconDemo | How to Use Icons | Loads an image in an action listener. Because loading an image can take a while, this program uses a SwingWorker to load the image in a background thread. |
TableDialogEditDemo | How to Use Tables | Registers an action listener through a factory method on the OK button of a color chooser dialog. |
SliderDemo | How to Use Sliders | Registers an action listener on a timer that controls an animation loop. |
Previous page: Implementing Listeners for Commonly Handled Events
Next page: How to Write a Caret Listener
Introduction to Event Listeners
If you have read any of the component how-to pages, you probably already know the basics of event listeners.
Let us look at one of the simplest event handling examples possible. It is called Beeper, and it features a button that beeps when you click it.
Click the Launch button to run Beeper using Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the example index.
You can find the entire program in Beeper.java . Here is the code that implements the event handling for the button:
public class Beeper . implements ActionListener < . //where initialization occurs: button.addActionListener(this); . public void actionPerformed(ActionEvent e) < . //Make a beep sound. > >
The Beeper class implements the ActionListener interface, which contains one method: actionPerformed . Since Beeper implements ActionListener , a Beeper object can register as a listener for the action events that buttons fire. Once the Beeper has been registered using the Button addActionListener method, the Beeper 's actionPerformed method is called every time the button is clicked.
A More Complex Example
The event model, which you saw at its simplest in the preceding example, is quite powerful and flexible. Any number of event listener objects can listen for all kinds of events from any number of event source objects. For example, a program might create one listener per event source. Or a program might have a single listener for all events from all sources. A program can even have more than one listener for a single kind of event from a single event source.
Multiple listeners can register to be notified of events of a particular type from a particular source. Also, the same listener can listen to notifications from different objects.
Each event is represented by an object that gives information about the event and identifies the event source. Event sources are often components or models, but other kinds of objects can also be event sources.
Whenever you want to detect events from a particular component, first check the how-to section for that component. A list of the component how-to sections is here. The how-to sections give examples of handling the events that you are most likely to care about. In How to Use Color Choosers, for instance, you will find an example of writing a change listener to track when the color changes in the color chooser.
The following example demonstrates that event listeners can be registered on multiple objects and that the same event can be sent to multiple listeners. The example contains two event sources ( JButton instances) and two event listeners. One of the event listeners (an instance of a class called MultiListener ) listens for events from both buttons. When it receives an event, it adds the event's "action command" (which is set to the text on the button's label) to the top text area. The second event listener (an instance of a class called Eavesdropper ) listens for events on only one of the buttons. When it receives an event, it adds the action command to the bottom text area.
Try this:
- Click the Launch button to run MultiListener using Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the example index.
- Click the Blah blah blah button. Only the MultiListener object is registered to listen to this button.
- Click the You do not say! button. Both the MultiListener object and the Eavesdropper object are registered to listen to this button.
You can find the entire program in MultiListener.java . Here is the code that implements the event handling for the button:
public class MultiListener . implements ActionListener < . //where initialization occurs: button1.addActionListener(this); button2.addActionListener(this); button2.addActionListener(new Eavesdropper(bottomTextArea)); > public void actionPerformed(ActionEvent e) < topTextArea.append(e.getActionCommand() + newline); >> class Eavesdropper implements ActionListener < . public void actionPerformed(ActionEvent e) < myTextArea.append(e.getActionCommand() + newline); >>
In the above code, both MultiListener and Eavesdropper implement the ActionListener interface and register as action listeners using the JButton addActionListener method. Both classes' implementations of the actionPerformed method are similar: they simply add the event's action command to a text area.