Class Quiz Scorer
<< PickMe | OtherProjectsTrailIndex | ConsoleApplet >>
A completely random selection of someone in the class
import java.awt.*; import javax.swing.*; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class ClassQuizScorer extends JApplet implements ActionListener { private JButton[] plus,minus; private JPanel panel; private String[] names={"Jack", "Sean", "Martin", "Chris", "Sean"}; int[] scores; JLabel[] labels; private JLabel message; private JButton rand; public void init() { Container content=this.getContentPane(); content.setLayout(new GridLayout(names.length+1,2)); message=new JLabel(" ", JLabel.CENTER); rand=new JButton("Choose at Random"); rand.addActionListener(this); content.add(message); content.add(rand); labels = new JLabel[names.length]; scores = new int[names.length]; plus = new JButton[names.length]; minus = new JButton[names.length]; for (int i=0; i< names.length; i++) { labels[i]=new JLabel(names[i]+" "+scores[i], JLabel.CENTER); content.add(labels[i]); JPanel p=new JPanel(); plus[i]=createButton(i,1); p.add(plus[i]); minus[i]=createButton(i,-1); p.add(minus[i]); content.add(p); } } private JButton createButton(int index, int increment) { JButton button; if (increment>0) button = new JButton("Add to "+names[index]); else button = new JButton("Subtract from "+names[index]); button.addActionListener(this); return button; } public void actionPerformed(ActionEvent e) { if (e.getSource() == rand){ String s="I choose "+names[(int)(Math.random()*5)]; while (s.equals(message.getText())) s="I choose "+names[(int)(Math.random()*5)]; message.setText(s); } else for (int i=0; i< names.length; i++) if (e.getSource()==plus[i]){ scores[i]++; labels[i].setText(names[i]+" "+scores[i]); } else if (e.getSource()==minus[i]){ scores[i]--; labels[i].setText(names[i]+" "+scores[i]); } } }