Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Java ActionListener?
3.
Method of Java ActionListener
4.
How to write ActionListener
5.
Examples
5.1.
Implementation 1
5.2.
Implementation 2
5.3.
Implementation 3
6.
Java ActionListener Example: On Button click
7.
Java ActionListener Example: Using Anonymous class
8.
Frequently Asked Questions
8.1.
Is Java ActionListener interface?
8.2.
How to add Multiple Java ActionListener?
8.3.
Why swings are used in Java?
8.4.
Which command does not generate any events?
9.
Conclusion
Last Updated: Apr 30, 2024
Medium

Java ActionListener

Author yuvatimankar
1 upvote
Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

We all have seen interactive applications that perform some action whenever the mouse is in motion. But how do internal things work? How to implement them in Java? To answer all these questions, we have Java ActionListener. Java ActionListeer iis an interface in the java.awt.package, and it is useful in interacting with the user whenever any action is performed in an application.

In this article, we will learn about Java ActionListener, its declaration, and its methods with detailed examples. So let’s get started with our article.

Read More About, Basics of Java and Fibonacci Series in Java

What is Java ActionListener?

Java ActionListener is an interface in java.awt.event package. It is an type of class in Java that receives a notification whenever any action is performed in the application. Java ActionListener is alerted whenever the button or menu item is clicked. It is alerted against ActionEvent. Java ActionListener interface consists of only one method.

The following syntax can declare the Java ActionListener interface:

public class ActionListenerExample Implements ActionListener 

Check this out: Access modifiers in java

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Method of Java ActionListener

Whenever a button or menu is clicked, an object must be present in the program, which helps in implementing the interface. An event will be generated by clicking the menu or button; for this, we will use some methods. Java ActionListener consists of only one method, which is as follows:

public extract void actionPerformed(ActionEvent e)It is initiated automatically whenever we click on the registered component

How to write ActionListener

  1. Implement ActionListener Interface: Create a class that implements the ActionListener interface.
  2. Override actionPerformed Method: Implement the actionPerformed(ActionEvent e) method within the class. This method contains the code to execute when the action occurs.
  3. Register ActionListener: Register the ActionListener to the appropriate GUI component using the addActionListener() method.
  4. Handle Action Events: Write the logic inside the actionPerformed() method to handle the action events triggered by the user interaction with the GUI component.
  5. Perform Desired Actions: Define the actions to be performed when the event occurs, such as updating GUI components, performing calculations, or invoking other methods.

Examples

Let us have a look at some examples to understand the usage of Java ActionListener.

Implementation 1

In the below example, we have created a class ActionListenerExample whose task is to listen to the action on the output panel, as we can see we have written the text Coding Ninjas and in the output, it is clearly visible to us.

import java.awt.*;  
import java.awt.event.*;  

public class ActionListenerExample {  
public static void main(String[] args) {  
    Frame f=new Frame("ActionListener Example");  
    final TextField tf=new TextField();  
    tf.setBounds(50,50, 150,20);  
    Button b=new Button("Click Here");  
    b.setBounds(50,100,60,30);  
  
    b.addActionListener(new ActionListener(){  
    public void actionPerformed(ActionEvent e){  
            tf.setText("Coding Ninjas");  
    }  
    });  
    f.add(b);f.add(tf);  
    f.setSize(400,400);  
    f.setLayout(null);  
    f.setVisible(true);   
}  
}

 

Output:

Java ActionListener Output

Implementation 2

In the below example also, we are going to listen to the action on the screen with the help of some of the classes, the class here we have created is AwtListenerDemo so whenever we will click it will show in the output that the button is clicked.

package com.codingninjas.gui;
import java.awt.*;
import java.awt.event.*;


public class AwtListenerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;


   public AwtListenerDemo(){
      prepareGUI();
   }


   public static void main(String[] args){
      AwtListenerDemo  awtListenerDemo = new AwtListenerDemo();  
      awtListenerDemo.showActionListenerDemo();
   }


   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
   
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);


      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());


      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }


   private void showActionListenerDemo(){
      headerLabel.setText("Listener in action: ActionListener");      


      ScrollPane panel = new ScrollPane();      
      panel.setBackground(Color.magenta);            


      Button okButton = new Button("OK");


      okButton.addActionListener(new CustomActionListener());        
      panel.add(okButton);
      controlPanel.add(panel);


      mainFrame.setVisible(true); 
   }


   class CustomActionListener implements ActionListener{
      public void actionPerformed(ActionEvent e) {
         statusLabel.setText("Ok Button Clicked.");
      }
   }
}

 

Output:

Java ActionListener Output

Implementation 3

In the below example also, we are going to listen to the action on the screen with the help of some of the classes, the class here we have created is JActionListener so whenever we will click it will show in the output that the button is clicked.

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;
//new class that implements the ActionListener interface
public class JActionListenerExample implements ActionListener {
JButton btn;
JFrame frm;
JTextArea txt;
public JActionListenerExample() {
btn = new JButton("Click this button");
frm = new JFrame("Java ActionListener Example");
txt = new JTextArea(6, 41);
btn.addActionListener(this);
txt.setLineWrap(true);
// Setting layout
frm.setLayout(new BorderLayout());
// Adding textarea to the container
frm.add(txt, BorderLayout.NORTH);
// Add the button to the container
frm.add(btn, BorderLayout.SOUTH);
// Resize the window based on container size
frm.pack();
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Set visibility
frm.setVisible(true);
}


@Override
public void actionPerformed(ActionEvent ev) {
txt.setText(txt.getText().concat("User has clicked the button \n"));
}
public static void main(String args[]) {
JActionListenerExample jl = new JActionListenerExample();
} 
}

 

Output:

Java ActionListener Output

Try and compile it by yourself on java online compiler.

Java ActionListener Example: On Button click

import java.awt.*;
import java.awt.event.*;

public class ButtonClickExample extends Frame implements ActionListener {
    Button btn;

    public ButtonClickExample() {
        btn = new Button("Click Me");
        btn.setBounds(100, 150, 80, 30);
        add(btn);
        btn.addActionListener(this);
        setSize(300, 300);
        setLayout(null);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        System.out.println("Button clicked!");
    }

    public static void main(String[] args) {
        new ButtonClickExample();
    }
}

Explanation:

  • A Java AWT Frame is created with a Button labeled "Click Me".
  • An instance of the ButtonClickExample class is created.
  • ActionListener is implemented, and the actionPerformed method is overridden to print a message when the button is clicked.
  • The ActionListener is registered with the button using the addActionListener method.
  • The Frame is displayed.

Java ActionListener Example: Using Anonymous class

import java.awt.*;
import java.awt.event.*;

public class ButtonClickExample {
    public static void main(String[] args) {
        Frame f = new Frame("Button Example");
        final TextField tf = new TextField();
        tf.setBounds(50, 50, 150, 20);
        Button b = new Button("Click Me");
        b.setBounds(50, 100, 80, 30);
        b.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                tf.setText("Button Clicked!");
            }
        });
        f.add(b);
        f.add(tf);
        f.setSize(400, 400);
        f.setLayout(null);
        f.setVisible(true);
    }
}

Explanation:

  • A Java AWT Frame is created with a Button labeled "Click Me" and a TextField.
  • An anonymous ActionListener is created and attached to the button using the addActionListener method.
  • Inside the actionPerformed method of the anonymous ActionListener, the text of the TextField is set to "Button Clicked!" when the button is clicked.
  • The Frame is displayed.

Frequently Asked Questions

Is Java ActionListener interface?

Yes, Java ActionListener is an interface. It is the listener interface for obtaining action events.

How to add Multiple Java ActionListener?

First, we have to create a class that implements Java ActionListener and extends JFrame, next we have to create a number of these JFrames and store them in an array and at last, we have to create a JFrame component that has a Jbutton as its field.

Why swings are used in Java?

Swings are used for creating window-based applications. Swing in java is part of the Java foundation class which is platform-independent and lightweight. 

Which command does not generate any events?

The command known as TextArea objects does not generate any events.

Conclusion

This article extensively discussed Java ActionListener and its method. We started with an introduction to Java ActionListener, then saw some of the methods of Java ActionListener, and after that, we have seen some examples of handling Java ActionListener. 

If you want to learn more on such topics, you can see Introduction to JavaBasics of Java, Why is Java Platform Independent, Hashcode Method in Java , Learn getting started with Java, and Learn OOPs in Java; also, you can enroll in the course Basics of Java with Data structure and algorithms. Also, you can visit our website, code studio!

You can also refer to our guided path on Coding Ninjas Studio to upskill yourself in Data structure and algorithmsCompetitive Programming, Javascriptand System Design.

Do upvote our blogs if you find them helpful and engaging!

Happy learning!

Previous article
Java MouseListener
Next article
MouseMotionListener
Live masterclass