So I wrote up a simple voting GUI, but I havent been able to figure out how to get it to display the current leader or how many votes they have. It displays the total number of votes correctly, however. Heres my code
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
/**
* @author rhyspj
*
*/
public class Election5 extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public class Candidate3 extends Candidate2 {
private static final long serialVersionUID = 1L;
public Candidate3(Color c, String name) {
super(c, name);
}
public int getVotes() {
return votes;
}
public String getName() {
return name;
}
}
private Vector<Candidate3> heroes;
private JButton tote;
public Election5() {
super();
setVisible(true);
setSize(600,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container me = getContentPane();
heroes = new Vector<Candidate3>();
heroes.add(new Candidate3(Color.red, "Spiderman"));
heroes.add(new Candidate3(Color.black, "Batman"));
heroes.add(new Candidate3(Color.magenta, "Thor"));
heroes.add(new Candidate3(Color.blue, "Captain America"));
heroes.add(new Candidate3(Color.green, "Ironman"));
heroes.add(new Candidate3(Color.pink, "Superman"));
tote = new JButton("Latest results appear (click me)");
tote.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tote.setText("Current leader is: " +getName()
+"with " +mostVotes() +" votes out of " +sumVotes());
}
});
me.setLayout(new GridLayout(0,2));
for (Candidate3 person : heroes) {
me.add(person);
}
me.add(tote);
validate();
}
public int mostVotes(){
int total = 0;
for (Candidate3 win : heroes) {
total = total + win.getVotes();
}
return total;
}
public int sumVotes() {
int total = 0;
for (Candidate3 hero : heroes) {
total = total + hero.getVotes();
}
return total;
}
public static void main(String[] args) {
new Election5();
}
}