/* DaGui1.java CIS 160 2014-10-23 David Klick Very basic GUI demonstration with listener for button. */ import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingUtilities; public class DaGui1 extends JFrame implements ActionListener { // Declare a global label so two different methods can access it. private JLabel label = null; // Create global counter to make state persistent. private int counter = 0; // Create a new object of ourself when program starts. public static void main(String[] args) { new DaGui1(); } // Default constructor public DaGui1() { // Create a thread to set up the GUI when the EDT // (Event Dispatch Thread) gets time. SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } // This method sets up and displays the GUI. public void createAndShowGUI() { // Get a container for the GUI components. Container c = getContentPane(); // Set the layout manager for the container. c.setLayout(new BorderLayout()); // Create the widgets. label = new JLabel("Hi"); JButton btn = new JButton("Klick me"); // Add this object as the event listener for the button. btn.addActionListener(this); // Add widgets to container. c.add(btn, BorderLayout.CENTER); c.add(label, BorderLayout.NORTH); // Set close operation and display GUI. setSize(500, 400); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); } // This method handles button clicks. public void actionPerformed(ActionEvent e) { // If number of clicks on the button is less than // 5, then display "Go away!", else end the program. counter++; if (counter < 5) { label.setText("Go away!"); } else { System.exit(0); } } }