Computer Science 523
Advanced Programming
Summer 2014, The College of Saint Rose
VotingMany Demo
A working demo of VotingMany will appear below. Click inside the applet to interact with it.
VotingMany BlueJ Project
Click here to download a BlueJ project for VotingMany.
VotingMany Source Code
The Java source code for VotingMany is below. Click on a file name to download it.
/* * Example VotingMany: expand the voting example to an arbitrary * number of candidates * * Jim Teresco, The College of Saint Rose, CSC 523, Summer 2014 * * $Id: VotingMany.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 VotingMany extends JApplet implements ActionListener { // a named constant for the number of candidates private static final int NUM_CANDIDATES = 5; // We need arrays for the buttons, counts, and labels private JButton[] buttons; private int[] votes; private JLabel[] labels; public void init() { Container contentPane = getContentPane(); // our array of vote tallies votes = new int[NUM_CANDIDATES]; for (int c = 0; c < NUM_CANDIDATES; c++) { votes[c] = 0; } // set up our labels in a JPanel in the center, use the // current font but make it bigger JPanel labelPanel = new JPanel(); labels = new JLabel[NUM_CANDIDATES]; for (int c = 0; c < NUM_CANDIDATES; c++) { labels[c] = new JLabel("Candidate " + (c+1) + ": 0"); } Font currentFont = labels[0].getFont(); Font newFont = new Font(currentFont.getFontName(), currentFont.getStyle(), 30); for (int c = 0; c < NUM_CANDIDATES; c++) { labels[c].setFont(newFont); labelPanel.add(labels[c]); } contentPane.add(labelPanel, BorderLayout.CENTER); // add our buttons in a JPanel too, set them up with our action listener JPanel buttonPanel = new JPanel(); buttons = new JButton[NUM_CANDIDATES]; for (int c = 0; c < NUM_CANDIDATES; c++) { buttons[c] = new JButton("Vote for " + (c+1)); buttons[c].addActionListener(this); buttonPanel.add(buttons[c]); } contentPane.add(buttonPanel, BorderLayout.SOUTH); } // our actionPerformed method now needs to deal with all of the // buttons public void actionPerformed(ActionEvent e) { // we need to know which button was pressed so let's check each for (int c = 0; c < NUM_CANDIDATES; c++) { if (e.getSource() == buttons[c]) { votes[c]++; labels[c].setText("Candidate " + (c+1) + ": " + votes[c]); // no need to continue once we've found a match return; } } } }