Java Stream How to - Simplify event handler for Swing








Question

We would like to know how to simplify event handler for Swing.

Answer

//from  w  ww .ja  v a 2 s  .c o m
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;


public class Main {

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        JButton button = new JButton("Click me");
        button.addActionListener(e -> JOptionPane.showMessageDialog(frame, "Hello World!"));
        frame.getContentPane().add(button);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
}