An action listener is a Java interface that allows you to specify an action to be performed when an event occurs. To create an action listener in Java, you need to do the following:
ActionListener
interface. The ActionListener
interface has a single method called actionPerformed
, which is called when the action event occurs.public class MyActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { // Code to be executed when the action event occurs } }
MyActionListener listener = new MyActionListener();
addActionListener
method of the JButton
class.JButton button = new JButton("Click me"); button.addActionListener(listener);
Now, whenever the button is clicked, the actionPerformed
method of the MyActionListener
class will be called.
You can also create an action listener using an anonymous inner class, like this:
button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Code to be executed when the action event occurs } });
In this case, you don't need to define a separate class for the action listener. The action listener is created and attached to the button in a single line of code.