header

ActionListener Interface

Import

import java.awt.event.*;

Responding to Action Events

The ActionListener interface enables your program to respond to user actions such as entering data in a text field or clicking on a button. Such an action causes the corresponding component to trigger an ActionEvent. To enable your program to respond to an ActionEvent, you must complete these three steps:

Step 1

Include an implements ActionListener clause in the class declaration:

public class myClass implements ActionListener
{
    // Class code goes here
}

Step 2

Enable your program to listen for action events on a component by invoking the component's addActionListener method:

myComponent.addActionListener(this);

The this parameter is a self-reference to your program. That is, you are registering your application to "listen" for user interaction with the component.

Step 3

Implement the ActionListener interface's only method:

public void actionPerformed(ActionEvent e)
{
    // Method code goes here
}

This method contains the code that responds to the action events generated by those components for which your program is registered as an ActionListener. The ActionEvent parameter is generated by the runtime environment and the getSource( ) method of this object can be used to determine which component generated the event (assuming your interface has more than one component with which the user can interact).

Example

In the Java code below, I've illustrated how to set up an exit button. This line goes in the declarations section of the application:

private JButton cmdExit;

The next two lines go in the method that creates the interface:

cmdExit = new JButton("Exit");
cmdExit.addActionListener(this);

This last section of code goes in the actionPerformed method:

public void actionPerformed(ActionEvent ae)
{
    Object source = ae.getSource();
    if (source.equals(cmdExit))
    {
        System.exit(0);
    }
}