Lab 1 -
Vote Counter (java)
Maximum Points = 10
The
purpose of this lab is to review the development of a GUI program using the
Java programming language. This lab exercise
creates a GUI with two buttons representing two candidates (Red and Green) in
an election or popularity contest. The program computes the number of times
each button is pressed. The program uses one listener and its ActionPerformed method will determine which button is
pressed.
The
files VoteCounter.java and VoteCounterPanel.java contain code for
one candidate - Red. Save them to your directory and do the following:
//*********************************************************
// VoteCounter.java
//
// Demonstrates
a graphical user interface and event
// listeners to tally
votes for two candidates, Red and Green.
// [modified from a
lab assignment in the Lewis/Loftis lab manual]
//*********************************************************
import javax.swing.JFrame;
public class VoteCounter
{
//----------------------------------------------
// Creates the
main program frame.
//----------------------------------------------
public static void
main(String[] args)
{
JFrame frame
= new JFrame("Vote Counter");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new VoteCounterPanel());
frame.pack();
frame.setVisible(true);
}
}
//*********************************************************
// VoteCounterPanel.java
//
// Panel for the GUI
that tallies votes for two candidates,
// Red and Green
//*********************************************************
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class VoteCounterPanel extends
JPanel
{
private int votesForRed;
private JButton red;
private JLabel labelRed;
//----------------------------------------------
// Constructor: Sets up the GUI.
//----------------------------------------------
public VoteCounterPanel()
{
votesForRed
= 0;
red = new JButton("Vote for Red");
red.addActionListener(new VoteButtonListener());
labelRed
= new JLabel("Votes for Red: " + votesForRed);
add(red);
add(labelRed);
setPreferredSize(new Dimension(300, 40));
setBackground(Color.cyan);
}
//***************************************************
// Represents a listener for button push
(action) events
//***************************************************
private class VoteButtonListener implements ActionListener
{
//----------------------------------------------
// Updates the appropriate vote counter
when a
// button is pushed for one of the
candidates.
//----------------------------------------------
public void actionPerformed(ActionEvent
event)
{
votesForRed++;
labelRed.setText("Votes
for Red: " + votesForRed);
}
}
}
(Due before 8 am on Tuesday, January 21, 2014) Submit your .java files containing your program and your timesheet documenting your time to the dropbox in CougarView.
Grades are determined using the following scale:
Grading Rubric (Word document)