Download to read offline
![Adding a action listener to button
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.event.ActionListener;
import java.awt.Component;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class action_listner_implementation extends JFrame {
action_listner_implementation()
{ setSize(200, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button1 = new JButton("Message dialog");
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog((Component) e.getSource(), "Thank
you!");}});
JPanel jp=new JPanel();
jp.add(button1);
getContentPane().add(jp);
}
public static void main(String[] args) {
action_listner_implementation a=new action_listner_implementation();
a.setVisible(true);
}
}](https://image.slidesharecdn.com/addingaactionlistenertobutton-160615122608/75/Adding-a-action-listener-to-button-1-2048.jpg)
This document shows how to add an action listener to a button in Java. It imports necessary classes like JButton and ActionListener. It creates a JFrame with a button that displays a message dialog when clicked. The button is given an action listener that calls showMessageDialog when the button's actionPerformed method is triggered. The button is added to a panel and frame for display.