Computer Science 523
Advanced Programming
Summer 2014, The College of Saint Rose
VotingManyLayout Demo
A working demo of VotingManyLayout will appear below. Click inside the applet to interact with it.
VotingManyLayout BlueJ Project
Click here to download a BlueJ project for VotingManyLayout.
VotingManyLayout Source Code
The Java source code for VotingManyLayout is below. Click on a file name to download it.
/*
* Example VotingManyLayout: a prettier version of the many voting example
*
* Jim Teresco, The College of Saint Rose, CSC 523, Summer 2014
*
* $Id: VotingManyLayout.java 2381 2014-06-18 12:48:37Z terescoj $
*/
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
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 VotingManyLayout 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();
contentPane.setLayout(new GridLayout(NUM_CANDIDATES+1, 1));
// 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 but this time add them to the GridLayout so we have
// them all in a column
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);
contentPane.add(labels[c]);
}
// add our buttons in a JPanel, 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]);
}
// this will add to the last slot in the GridLayout
contentPane.add(buttonPanel);
contentPane.validate();
}
// 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;
}
}
}
}