Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Java ActionListeer is an interface in the java.awt.package, and it is useful in interacting with the user whenever any action is performed in an application. It listens for actions like button presses or menu selections. Implementing the actionPerformed() method allows the program to respond to user interactions dynamically, enhancing user experience.
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.
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
Method of Java ActionListener in Java
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 in Java
Implement ActionListener Interface: Create a class that implements the ActionListener interface.
Override actionPerformed Method: Implement the actionPerformed(ActionEvent e) method within the class. This method contains the code to execute when the action occurs.
Register ActionListener: Register the ActionListener to the appropriate GUI component using the addActionListener() method.
Handle Action Events: Write the logic inside the actionPerformed() method to handle the action events triggered by the user interaction with the GUI component.
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 of ActionListener in Java
Let us have a look at some examples to understand the usage of Java ActionListener.
Example -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:
Example - 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:
Example - 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();
}
}
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
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.
Can ActionListener handle multiple actions from different components?
Yes, ActionListener can handle multiple actions if different components (like buttons) are registered with the same ActionListener. The event source can be identified within the actionPerformed() method.
Can ActionListener be used in command-line applications?
No, ActionListener is specifically for handling GUI events in graphical applications. Command-line applications do not have a GUI, so ActionListener is not applicable in that context.
Conclusion
Java ActionListener is a powerful interface in the java.awt.event package that facilitates interaction within Java applications. 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.