ActionListener in Java is a class that is responsible for handling all action events such as when the user clicks on a component. Mostly, action listeners are used for JButtons.
An ActionListener can be used by the implements keyword to the class definition. It can also be used separately from the class by creating a new class that implements it. It should also be imported to your project.
The method actionPerformed handles all the actions of a component, and inside this method, you will define or write your own codes that will be executed when an action occurred. Here’s an example on how to implement ActionListener in Java.
package com.javapointers.javase; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTextArea; public class ActionListenerTest implements ActionListener { JButton button; JFrame frame; JTextArea textArea; public ActionListenerTest() { button = new JButton("Click Me"); frame = new JFrame("ActionListener Test"); textArea = new JTextArea(5, 40); button.addActionListener(this); textArea.setLineWrap(true); frame.setLayout(new BorderLayout()); frame.add(textArea, BorderLayout.NORTH); frame.add(button, BorderLayout.SOUTH); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { textArea.setText(textArea.getText().concat("You have clicked the button\n")); } public static void main(String args[]) { ActionListenerTest test = new ActionListenerTest(); } }
when we run our program, the UI will be:
Explanation:
public class ActionListenerTest implements ActionListener {
an action listener should be implemented in a class before you can use it. Just add the implements keyword and the listener.
button.addActionListener(this);
means that the component button will be added to the components that are being tracked for an action event. A component should add an action listener so that you can execute codes whenever a user clicks the component. A component without an action listener will not be monitored.
public void actionPerformed(ActionEvent e) {}
this method is already defined in ActionListener class and we have just override it. Here, you will define what will your program do when the user clicks the component being monitored for an action event.
The next tutorial is about implementing a Mouse Listener that is used when we want to do something whenever a mouse hovers to the component and other actions.