ActionListener in Java

Master Java's ActionListener interface to handle action events

Format
mla apa chicago
Your Citation
Leahy, Paul. "ActionListener in Java." ThoughtCo, Jan. 16, 2017, thoughtco.com/actionlistener-2033990. Leahy, Paul. (2017, January 16). ActionListener in Java. Retrieved from https://www.thoughtco.com/actionlistener-2033990 Leahy, Paul. "ActionListener in Java." ThoughtCo. https://www.thoughtco.com/actionlistener-2033990 (accessed September 22, 2017).

The ActionListener interface is used for handling action events. For example, it's used by a JButton for button clicks, by JCheckbox for checking and unchecking, by a JMenuItem when an option is picked and many other graphical components.

It's a simple interface with only one method:

public interface ActionListener extends EventListener{

     public void actionPerformed(ActionEvent e);

}

To use the ActionListener interface, it must be implemented by a class.

There are several ways to do this -- creating a new class, using the class the graphical component is in, using an inner class or using an anonymous inner class. The code that needs to be run when the action event occurs is placed inside the actionPerformed method.

Then the class implementing the ActionListener interface must be registered with the graphical component through the addActionListener method. For example, the following class implements the ActionListener class and the JButton uses the class to handle its button click events:

public class SimpleCalc implements ActionListener{

    public SimpleCalc()
    {
        JButton aButton = new JButton("A Button");
        aButton.setActionCommand("A Button);
        aButton.addActionListener(this);
    }

    public void actionPerformed(ActionEvent event)
    {
       //put code to run on the button click here      
    }
}

See the Simple Calculator Handling Button Events for a step-by-step example of the use of implementing an ActionListener by using the containing class, an inner class and an anonymous class.

 The full Java code listing can be found in a Simple Calculator Example Program.