In this tutorial, we will learn how to implement ActionListener Interface in Java. Before moving ahead to our tutorial, let’s quickly look at some of the basic concepts about ActionListener, actionPerformed(), ActionEvent etc.
What is ActionListener in Java
ActionListener in Java is an interface that listens for and handles all the Action Events generated by the components, such as clicking on the specific component by the user.
An ActionListener interface is mainly used with Java JButtons, which means what operations should be performed when the user clicks on the button (Java Button Click Event). The ActionListener interface is located in the java.awt.event package, and we need to import that package into our program if we want to implement the ActionListner interface.
What is actionPerformed in Java
The ActionListener interface contains only its one abstract method, which is actionPerformed(ActionEvent e), which means if we are implementing the ActionListener interface in our class, then we have to override its abstract method actionPefromed in that class which takes a single argument of type ActionEvent (A class defined in package java.awt.event). ActionEvent object provides information about the event, and its source.
Action Event Class
Method | Description |
public String getActionCommand() | Returns the command string associated with this action |
Object getSource() | Returns a reference to the object that fired the event |
public int getModifiers() | Returns an integer value which the user was pressing when the during action event. |
When any Action event occurs like for example, when the user clicks on the button(object), then that object’s actionPerformed() method is invoked, and the behavior we want in response to the action event is coded inside the actionPerformed() method.
Now let’s learn how to implement ActionListener in Java with step-by-step explanations.
How to implement ActionListener in Java (Steps)
There are two ways by which we can write or use the ActionListener interface in our class.
- By implementing the ActionListener interface in the class.
- By using the anonymous inner class.
Now let’s understand both the ways with example programs and detailed step-by-step explanations.
By implementing the ActionListener in the class
This includes three steps and lets us see all the three steps that we need to have in our program.
Step 1 – Declaring an Event handler class and Implementing the ActionListener interface in that class using the implements keyword.
1 |
public class classname implements ActionListener |
Step 2 – Registering or adding one or more components with the Listener using the addActionListener() method, which takes an argument, and in the argument, we need to pass the instance of the event handler class.
1 |
component.addActionListener(instanceOfEventHandlerClass) |
Step 3 – Overriding the method actionPerformed(ActionEvent e) in the class in which the ActionListener interface has been implemented. When the user clicks on any of the components, the desired code which we want in response related to that particular component is coded inside the actionPerformed() method.
1 2 3 4 5 |
public void actionPerformed(ActionEvent e){ //Desired code inside here } |
Now let us see the example program for this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
//importing all the packages import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /*Declaring Event Handler class and implementing ActionListener interface */ public class ActionListenerExample implements ActionListener { int count=0; //declaring and initializing counter variable //Creating objects of all the components JFrame frame = new JFrame("Action Listener"); JButton redButton= new JButton("Red"); JButton greenButton=new JButton("Green"); JButton blueButton=new JButton("Blue"); JLabel label= new JLabel(); //Creating constructor of the class ActionListenerExample(){ //Setting properties of JFrame frame.setSize(500,500); frame.getContentPane().setLayout(null); frame.setLocationRelativeTo(null); frame.setResizable(false); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Setting properties of RedButton redButton.setBounds(60,300,100,40); redButton.setFocusable(false); redButton.setFont(new Font("Arial",Font.BOLD,20)); frame.add(redButton); //Setting properties of GreenButton greenButton.setBounds(190,300,100,40); greenButton.setFocusable(false); greenButton.setFont(new Font("Arial",Font.BOLD,20)); frame.add(greenButton); //Setting properties of BlueButton blueButton.setBounds(320,300,100,40); blueButton.setFocusable(false); blueButton.setFont(new Font("Arial",Font.BOLD,20)); frame.add(blueButton); //Setting properties of Label label.setBounds(170,350,200,40); label.setFont(new Font("Arial",Font.BOLD,20)); frame.add(label); //Registering listener for components redButton.addActionListener(this); greenButton.addActionListener(this); blueButton.addActionListener(this); } //Overriding actionPerformed() method @Override public void actionPerformed(ActionEvent e) { //Incrementing counter when the user clicks on any Button count++; //Code for Red Button if(e.getSource()==redButton){ //changing the background color of JFrame to Red frame.getContentPane().setBackground(Color.red); //Setting the label text with number of times the button clicked label.setText("No of clicks "+count); } //Code for Green Button else if(e.getSource()==greenButton){ //changing the background color of JFrame to Green frame.getContentPane().setBackground(Color.green); //Setting the label text with number of times the button clicked label.setText("No of clicks "+count); } //Code for Blue Button else if(e.getSource()==blueButton){ //changing the background color of JFrame to Blue frame.getContentPane().setBackground(Color.blue); //Setting the label text with number of times the button clicked label.setText("No of clicks "+count); } } //main method of our program public static void main(String[] args){ //Creating object of the class ActionListenerExample listenerExample=new ActionListenerExample(); } } |
Explanations
- In the First step, we imported all the necessary packages for our program. We have implemented the ActionListener interface in our class, so we need to import java.awt.event package because this interface is located inside this package.
1 2 3 |
import javax.swing.*; import java.awt.*; import java.awt.event.*; |
- Next, we declared our Event handler class and implemented the ActionListener interface.
1 |
public class ActionListenerExample implements ActionListener |
- Since we have implemented the ActionListener interface in our class, Next, we need to override its only abstract method, which is actionPerformed(ActionEvent e) in that class. It takes a single argument of type ActionEvent (A class defined in package java.awt.event). ActionEvent object provides information about the event, and its source.
1 2 3 4 |
@Override public void actionPerformed(ActionEvent e) { } |
- Next, we created the constructor of our class and then created the main method and inside the main method created the object of the class.
- Next, we created objects of all the components we needed for our program. One JFrame, Three JButtons, One JLabel.
- Next, we set the properties for all the components and JFrame inside the constructor of our class.
- Next, we have registered all the buttons with Listener using the addActionListener() method. In the argument, it takes the instance of the class in which the ActionListener interface has been implemented, and since we are in the same class, we passed this as an argument. The components/Sources must be registered with Action Listener to receive notifications about a specific type of Event. Whenever the user clicks on the component, then that component fires an action event which is registered with Action Listener and thus invokes the method actioPerformed(), which is the only method in the ActionListener interface.
- Without registering with Action Listener, a component does not get monitored for any Action Event.
1 2 3 |
redButton.addActionListener(this); greenButton.addActionListener(this); blueButton.addActionListener(this); |
- Now what we want that when the user clicks on the button titled “Red”, then the background of the JFrame should be changed to red color. And same for Green and Blue button the color should be changed to green and blue respectively.
- As well as, whenever the user clicks on any of the buttons, how many times the buttons clicked will be displayed on the JLabel just below the buttons. For this, we have created the counter variable, and it will be incremented to one whenever the user clicks on any button.
- For this, all the desired code is coded inside the actionPerformed(ActionEvent e) method. To get the source of the event, we used the method getSource() using the object of ActionEvent class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
@Override public void actionPerformed(ActionEvent e) { //Incrementing counter when the user clicks on any Button count++; //Code for Red Button if(e.getSource()==redButton){ //changing the background color of JFrame to Red frame.getContentPane().setBackground(Color.red); //Setting the label text with number of times the button clicked label.setText("No of clicks "+count); } //Code for Green Button else if(e.getSource()==greenButton){ //changing the background color of JFrame to Green frame.getContentPane().setBackground(Color.green); //Setting the label text with number of times the button clicked label.setText("No of clicks "+count); } //Code for Blue Button else if(e.getSource()==blueButton){ //changing the background color of JFrame to Blue frame.getContentPane().setBackground(Color.blue); //Setting the label text with number of times the button clicked label.setText("No of clicks "+count); } } |
- Now, let’s run our program.
Output :
- As you can see in the above picture, when the button titled “Green” is clicked, The Background color of the JFrame changes to Green color, and the total number of clicks is displayed in the JLabel text just below the Buttons.
By Using the Anonymous inner Class
We can also implement the ActionListener interface in our class using the Anonymous inner class. It is the shortcut way, so we don’t need to follow the three steps as we did in the First example of implementing the ActionListener interface.
The syntax of implementing the ActionListener interface using the Anonymous inner class is as follows.
1 2 3 4 5 6 7 |
component.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //Desired code inside here } }); |
Now let’s implement the ActionListener interface using the anonymous inner class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
//importing all the packages import javax.swing.*; import java.awt.*; import java.awt.event.*; /*Declaring Event Handler class and implementing ActionListener interface */ public class ActionListenerExample { int count=0; //declaring and initializing counter variable //Creating objects of all the components JFrame frame = new JFrame("Action Listener"); JButton redButton= new JButton("Red"); JButton greenButton=new JButton("Green"); JButton blueButton=new JButton("Blue"); JLabel label= new JLabel(); //Creating constructor of the class ActionListenerExample(){ //Setting properties of JFrame frame.setSize(500,500); frame.getContentPane().setLayout(null); frame.setLocationRelativeTo(null); frame.setResizable(false); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Setting properties of RedButton redButton.setBounds(60,300,100,40); redButton.setFocusable(false); redButton.setFont(new Font("Arial",Font.BOLD,20)); frame.add(redButton); //Setting properties of GreenButton greenButton.setBounds(190,300,100,40); greenButton.setFocusable(false); greenButton.setFont(new Font("Arial",Font.BOLD,20)); frame.add(greenButton); //Setting properties of BlueButton blueButton.setBounds(320,300,100,40); blueButton.setFocusable(false); blueButton.setFont(new Font("Arial",Font.BOLD,20)); frame.add(blueButton); //Setting properties of Label label.setBounds(170,350,200,40); label.setFont(new Font("Arial",Font.BOLD,20)); frame.add(label); //implementing ActionListener for Red Button redButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { count++; //changing the background color of JFrame to Red frame.getContentPane().setBackground(Color.red); //Setting the label text with number of times the button clicked label.setText("No of clicks "+count); } }); //implementing ActionListener for Green Button greenButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { count++; //changing the background color of JFrame to Green frame.getContentPane().setBackground(Color.GREEN); //Setting the label text with number of times the button clicked label.setText("No of clicks "+count); } }); //implementing ActionListener for Blue Button blueButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { count++; //changing the background color of JFrame to Blue frame.getContentPane().setBackground(Color.BLUE); //Setting the label text with number of times the button clicked label.setText("No of clicks "+count); } }); } public static void main(String[] args){ ActionListenerExample listenerExample=new ActionListenerExample(); } } |
- Now, let’s run our program.
Output :
Why do we implement ActionListener in Java?
To check and determine whether the user has clicked on any specific components. It helps in what actions should be performed when the user clicks on any specific component ( like a Java Button).
Which is the Abstract method of ActionListener interface?
The actionPerformed(ActionEvent e) method is the only abstract method of the ActionListener interface.
So, guys, I am wrapping up this tutorial, “How to implement ActionListener in Java” Feel free to drop us a comment if you find something difficult to understand.
Related Articles
Java Button Click Event Tutorial
Login Form in Java Swing
Java Text to Speech
Java and MySQL Database Connectivity using Eclipse
Java and MySQL Database Connectivity using NetBeans
Registration Form in Java with Database Connectivity
Tic-Tac-Toe Game in Java with Source Code
Calculator App in Java using Swing
Java Interview Questions with PDF