How do I randomly select one of the three buttons when the highlighted one is cl
ID: 3760622 • Letter: H
Question
How do I randomly select one of the three buttons when the highlighted one is clicked.
public class StartEventHandler implements ActionListener {
private JFrame _win;
public StartEventHandler(JFrame w) {
_win = w;
}
@Override
public void actionPerformed(ActionEvent e) {
_win = new JFrame("Sequence Game");
JPanel p = new JPanel();
_win.setSize(250, 100);
p.setLayout(new GridLayout(0, 3));
JButton a;
JButton b ;
JButton c;
a = new JButton("A");
a.addActionListener(new AEventHandler(a));
b = new JButton("B");
b.addActionListener(new EventHandlerB(b));
c = new JButton("C");
c.addActionListener(new EventHandlerC(c));
p.add(a);
p.add(b);
p.add(c);
_win.add(p);
_win.setVisible(true);
int delay;
delay = 10000;
Timer t;
t = new Timer(delay, new CloseGame(_win));
t.start();
Random r;
r = new Random();
int x;
x = r.nextInt(3);
if (x == 0) {
a.setEnabled(true);
//b.setEnabled(false);
//c.setEnabled(false);
a.setForeground(Color.RED);
}
if (x == 1) {
b.setEnabled(true);
//a.setEnabled(false);
//c.setEnabled(false);
b.setForeground(Color.RED);
}
if (x == 2) {
c.setEnabled(true);
//a.setEnabled(false);
//b.setEnabled(false);
c.setForeground(Color.RED);
}
}
}
Explanation / Answer
to select one of the three buttons randomly we can add this code
in place of a.addActionListener(new AEventHandler(a));
and we can do the same for b and c.
rest of the code remains the same
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.