import java.awt.*; // basic awt classes import java.awt.event.*; // event classes import javax.swing.*; // swing classes /** * CSE 331 16su-17sp. Very simple demo of Swing event handling. * Create a window with a single button that prints a message when it's clicked. * Version 3 with an anonymous lambda function to handle user events. * (But now to count user events we need a global variable since the * lambda is not a complete object with persistent state.) * * @author Kevin Zatloukal, Hal Perkins */ public class ButtonDemo3 { private static int nEvents = 0; // number of button clicks /** Program that displays a message each time a button is pressed. */ public static void main(String[] args) { // Create new window and set it to exit from application when closed JFrame frame = new JFrame("Button Demo"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); // Create a new button with label "Hit me" and string "OUCH!" to be // returned as part of each action event. JButton button = new JButton("Hit me"); button.setActionCommand("OUCH!"); // Register an anonymous function to listen for button clicks button.addActionListener(e -> { nEvents++; System.out.println(e.getActionCommand() + " " + nEvents); }); // Add button to the window and make it visible frame.add(button); frame.pack(); frame.setVisible(true); } }