Computer Science 523
Advanced Programming
Summer 2014, The College of Saint Rose
Voting Demo
A working demo of Voting will appear below. Click inside the applet to interact with it.
Voting BlueJ Project
Click here to download a BlueJ project for Voting.
Voting Source Code
The Java source code for Voting is below. Click on a file name to download it.
/*
* Example Voting: demonstration of multiple buttons and a slightly more
* interesting layout
*
* Jim Teresco, The College of Saint Rose, CSC 523, Summer 2014
*
* $Id: Voting.java 2381 2014-06-18 12:48:37Z terescoj $
*/
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Voting extends JApplet implements ActionListener {
// We need to remember 2 buttons, 2 ints, and 2 labels to cast and track votes
private JButton aButton, bButton;
private int aVotes, bVotes;
private JLabel aLabel, bLabel;
public void init() {
Container contentPane = getContentPane();
aVotes = 0;
bVotes = 0;
// set up our labels in a JPanel in the center, use the
// current font but make it bigger
JPanel labelPanel = new JPanel();
aLabel = new JLabel("A: 0");
bLabel = new JLabel("B: 0");
Font currentFont = aLabel.getFont();
Font newFont = new Font(currentFont.getFontName(), currentFont.getStyle(), 30);
aLabel.setFont(newFont);
bLabel.setFont(newFont);
labelPanel.add(aLabel);
labelPanel.add(bLabel);
contentPane.add(labelPanel, BorderLayout.CENTER);
// and some buttons in a JPanel too, set them up with our action listener
JPanel buttonPanel = new JPanel();
aButton = new JButton("Vote for A");
bButton = new JButton("Vote for B");
aButton.addActionListener(this);
bButton.addActionListener(this);
buttonPanel.add(aButton);
buttonPanel.add(bButton);
contentPane.add(buttonPanel, BorderLayout.SOUTH);
}
// our actionPerformed method now needs to deal with both
// buttons
public void actionPerformed(ActionEvent e) {
// we need to know which button was pressed -- the ActionEvent
// can tell us with its getSource method
if (e.getSource() == aButton) {
aVotes++;
aLabel.setText("A: " + aVotes);
}
else {
bVotes++;
bLabel.setText("B: " + bVotes);
}
}
}