ActionListener in Java

In Java, an ActionListener is used to respond to button clicks and other similar user actions. It allows us to define what should happen when a specific event, like a button click, occurs. Following is an example of how we can use ActionListener to respond when user clicks the button:

Import Required Libraries

First, import the necessary libraries to work with Swing components and ActionListener:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

Create a JFrame

Create a JFrame (the main window) to hold our GUI components:

public class ActionListenerDemo {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Button Click Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.setLayout(new FlowLayout());

        // Create a button and add ActionListener
        JButton button = new JButton("Click Me");
        button.addActionListener(new MyActionListener());

        frame.add(button);
        frame.setVisible(true);
    }
}

Implement ActionListener

Create a class that implements the ActionListener interface to define the action that should occur when the button is clicked:

class MyActionListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        // Code to execute when the button is clicked
        JOptionPane.showMessageDialog(null, "Button Clicked!");
    }
}

Final Code

If we combine all the steps then the final code looks like below:

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class ActionListenerDemo {
	public static void main(String[] args) {
        JFrame frame = new JFrame("Button Click Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.setLayout(new FlowLayout());

        // Create a button and add ActionListener
        JButton button = new JButton("Click Me");
        button.addActionListener(new MyActionListener());

        frame.add(button);
        frame.setVisible(true);
    }
}

class MyActionListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        // Code to execute when the button is clicked
        JOptionPane.showMessageDialog(null, "Button Clicked!");
    }
}

After executing the above code the output looks like below:

ActionListener in Java ActionListener Demo

Sharing Is Caring: