import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * Java demo showing the use of a button and window listener * Both listeners are triggered by events that happen asynchronously * demo adapted from https://www.tutorialspoint.com/how-to-add-action-listener-to-jbutton-in-java * modified Nov 2022 gtowell **/ public class SD { private JFrame frame; private JLabel statusLabel; int counter=0; public SD(){ } public static void main(String[] args){ SD swingControlDemo = new SD(); swingControlDemo.showButtonDemo(); } /** * Set up the JFrame and lay out components **/ private void prepareGUI(){ frame = new JFrame(Thread.currentThread().getName()); frame.setSize(500,500); frame.setLayout(new GridLayout(3, 1)); frame.addWindowListener(new WindowAdapter() { // Create an instance of WindowAdapter and override the default implementation of windowClosing method public void windowClosing(WindowEvent windowEvent) { System.out.println(Thread.currentThread().getName()); System.exit(0); } }); statusLabel = new JLabel("",JLabel.CENTER); statusLabel.setSize(350,100); frame.add(statusLabel); frame.setVisible(true); } /** * Add a button and a button listener **/ private void showButtonDemo(){ prepareGUI(); JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // create an instance of ActionListener and give a custom implementation of actionPerformed method counter++; statusLabel.setText(String.format("Clicked %d Thread:%s", counter, Thread.currentThread().getName())); } }); frame.add(okButton); frame.setVisible(true); } }