Java Swing How to - Add click event handler pre JDK 8 to JButton








Question

We would like to know how to add click event handler pre JDK 8 to JButton.

Answer

/*from   w w w .  j  av  a2 s .  c o  m*/
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JOptionPane;
public class Main {
  public static void main(final String args[]) {
    JButton button = new JButton("Test");

    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println("Button pressed");
      }
    });

    
    JOptionPane.showMessageDialog(null, button);
  }
}