Computer Science 523
Advanced Programming

Summer 2014, The College of Saint Rose

ButtonClickCounter Demo

A working demo of ButtonClickCounter will appear below. Click inside the applet to interact with it.



ButtonClickCounter BlueJ Project

Click here to download a BlueJ project for ButtonClickCounter.


ButtonClickCounter Source Code

The Java source code for ButtonClickCounter is below. Click on a file name to download it.


ButtonClickCounter.java

/*
 * Example ButtonClickCounter: a JButton and a JLabel that
 * we'll use to track the number of times the button has been
 * pressed.
 *
 * Jim Teresco, The College of Saint Rose, CSC 523, Summer 2014
 *
 * $Id: ButtonClickCounter.java 2379 2014-06-17 03:52:55Z terescoj $
 */

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;

public class ButtonClickCounter extends JApplet implements ActionListener {
    
    // Just as with other custom classes, we can introduce instance 
    // variables that have a class scope and which will retain their
    // values throughout the life of this class
    private int clickCount;
    private JLabel clickCountLabel;
    
    public void init() {
        Container contentPane = getContentPane();
        
        // In this init method, we'll add a JLabel and a JButton to our pane.
        // Note that we only need the JButton reference within the init method,
        // so it is a local variable, but we'll need the JLabel later, so
        // it is an instance varable.
        JButton button = new JButton("Press Here!");
        contentPane.add(button, BorderLayout.SOUTH);
        
        // The key to event-driven programming: we tell the button who
        // to tell when someone presses it.  We specify an instance of
        // a class that implements ActionListener, which means that the
        // class is guaranteed to have an actionPerformed method.  Here,
        // we specify "this", as the current class implements ActionListener
        // so we want the button to call the actionPerformed method of
        // this class when it gets pressed.
        button.addActionListener(this);
        
        clickCount = 0;
        clickCountLabel = new JLabel("0 clicks");
        contentPane.add(clickCountLabel, BorderLayout.CENTER);
        
    }
    
    // This method is the one that will be called when the button is pressed.
    // By stating "implements ActionPerformed" in the class header, we are
    // promising Java that we'll be providing this exact method.
    public void actionPerformed(ActionEvent e) {
        
        // if someone presses the button, we'll increment our click counter
        // and update the label to show the new count
        clickCount++;
        clickCountLabel.setText(clickCount + " clicks");
        
    }
}