import javax.swing.*; /** * Class to test simple use of a button. * It should show a count of the button clicks in the label. */ public class ButtonTest extends JPanel { JLabel countLabel; JButton button; public ButtonTest() { countLabel = new JLabel("0"); button = new JButton("Click me"); add(button); add(countLabel); } // Set up main window and add our components. public static void buildGUI() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setContentPane(new ButtonTest()); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { // A thread is a single sequence of logic within a program. A single // program can have multiple threads executing concurrently. The Swing // library is not thread safe, meaning that we can't work with it in // multiple concurrent threads. Almost all Swing code must execute in a // special thread called the event dispatch thread. The invokeLater // method allows us to run code on that thread, to make sure that no // errors can occur due to threading issues (even though for our simple // program such an error is very unlikely to happen). The input makes // use of the Runnable interface, which we're creating an anonymous // class to implement. SwingUtilities.invokeLater(new Runnable() { @Override public void run() { buildGUI(); } }); } }