import java.awt.Color; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; //------------------------------------------------------------------------- /** * Demonstrates a graphical user interface and an event listener. * * @author John Lewis * @version 2010.02.08 */ public class PushCounterPanel extends JPanel { //~ Instance/static variables ............................................. private int count; private JButton push; private JLabel label; //~ Constructors .......................................................... // ---------------------------------------------------------- /** * Sets up the GUI. */ public PushCounterPanel() { count = 0; push = new JButton("Push Me!"); push.setName("button"); push.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { increment(); } }); label = new JLabel("Pushes: " + count); label.setName("count"); add(push); add(label); setPreferredSize(new Dimension(300, 40)); setBackground(Color.cyan); } public void increment() { count++; label.setText("Pushes: " + count); } //~ Private methods/declarations .......................................... // ---------------------------------------------------------- /** * Represents a listener for button push (action) events. */ private class ButtonListener implements ActionListener { // ---------------------------------------------------------- /** * Updates the counter and label when the button is pushed. * @param event The GUI event, which is ignored by this method. */ public void actionPerformed(ActionEvent event) { increment(); } } }