A good way would be to create an array that hold the values chosen. Each time a
value is picked, have the box's value be set to the next value in the array.
You could then set up two more variables, one for each candidate. Within a for
loop you could step through the array and check each value. For each
value,increment the appropriate variable by one like this: candidate++.
Can someone please tell me how I would code counters in this code?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class vote {
public static void main(String[] args) {
JFrame f = new JFrame(" PRESIDENTIAL POLL: Today, I vote for");
f.setSize(600, 200);
f.setLocation(300, 200);
f.addWindowListener(new WindowAdapter( ) {
public void windowClosing(WindowEvent we) { System.exit(0); }
});
JPanel entreePanel = new JPanel( );
final ButtonGroup entreeGroup = new ButtonGroup( );
JRadioButton radioButton;
entreePanel.add(radioButton = new JRadioButton("John Kerry"));
radioButton.setActionCommand("John Kerry");
entreeGroup.add(radioButton);
entreePanel.add(radioButton = new JRadioButton("George Bush"));
radioButton.setActionCommand("George Bush");
entreeGroup.add(radioButton);
entreePanel.add(radioButton = new JRadioButton("neither", true));
radioButton.setActionCommand("neither");
entreeGroup.add(radioButton);
final JPanel condimentsPanel = new JPanel( );
condimentsPanel.add(new JCheckBox("I am registered to vote"));
//condimentsPanel.add(new JCheckBox("Mustard"));
//condimentsPanel.add(new JCheckBox("Pickles"));
JPanel orderPanel = new JPanel( );
JButton orderButton = new JButton("Submit Vote");
orderPanel.add(orderButton);
Container content = f.getContentPane( );
content.setLayout(new GridLayout(3, 1));
content.add(entreePanel);
content.add(condimentsPanel);
content.add(orderPanel);
orderButton.addActionListener(new ActionListener( ) {
public void actionPerformed(ActionEvent ae) {
String entree =
entreeGroup.getSelection().getActionCommand( );
System.out.println("I cast my vote for " + entree + ".");
Component[] components = condimentsPanel.getComponents( );
for (int i = 0; i < components.length; i++) {
JCheckBox cb = (JCheckBox)components[i];
if (cb.isSelected( ))
System.out.println("" + cb.getText( ) + ".");
}
}
});
f.setVisible(true);
}
}