The following is the same as the PushCounter example on pages
192 and 193 of the textbook except it assumes that pushing the button
is a vote for Blue (and all identifiers have been changed to reflect
this). Also rather than instantiating the listener object as a parameter
in the invocation of addActionListener, a listener object named
voteListener has been instantiated and it has been passed as
the parameter.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class VoteCounterPanel extends JPanel
{
private int votesForBlue;
private JLabel labelBlue;
private JButton blue;
// ------------------------------------------------------------
// Sets up the GUI
// ------------------------------------------------------------
public VoteCounterPanel ()
{
votesForBlue = 0;
blue = new JButton ("Vote for Blue!");
VoteButtonListener voteListener = new VoteButtonListener();
blue.addActionListener (voteListener);
labelBlue = new JLabel ("Votes for Blue: " + votesForBlue);
add (blue);
add (labelBlue);
setBackground (Color.white);
}
// *******************************************************************
// Represents a listener for button push actions
// *******************************************************************
private class VoteButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
votesForBlue++;
labelBlue.setText ("Votes for Blue: " + votesForBlue);
}
}
}
Suppose we wanted to add a second button to the panel, one for
candidate Red. We would need three new instance variables - a vote counter
for Red, a button, and a label. Add code to the above to:
- declare the 3 new instance variables
- initialize/instantiate them in the constructor
- add them to the panel
- add the voteListener object to the new button so it will
now listen for both buttons being clicked (NOTE: don't instantiate a new
listener object - use the one already there)