import javax.swing.*; import java.awt.event.*; public class MyButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "Button Pressed"); } } public class MyFrame extends JFrame { public MyFrame() { JButton myButton = new JButton("Click Me"); myButton.addActionListener(new MyButtonListener()); add(myButton); } }
import javax.swing.*; import java.awt.event.*; public class MyFrame extends JFrame implements ActionListener { public MyFrame() { JButton myButton = new JButton("Click Me"); myButton.addActionListener(this); add(myButton); } public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "Button Pressed"); } }This example shows how to implement an ActionListener by implementing the interface in the same class as the JButton. When the button is clicked, the actionPerformed method is called and a dialog box is displayed. Package Library: javax.swing