我试图将交通灯由红色变为黄色并在绿色中重复,并通过按下一个按钮来启动此过程。这是我的代码:更改交通灯状态java切换按钮
public class TrafficLight extends JFrame implements ActionListener {
JButton b1, b2, b3;
Signal green = new Signal(Color.green);
Signal yellow = new Signal(Color.yellow);
Signal red = new Signal(Color.red);
public TrafficLight(){
super("Traffic Light");
getContentPane().setLayout(new GridLayout(2, 1));
b1 = new JButton("Change State");
b1.addActionListener(this);
green.turnOn(false);
yellow.turnOn(false);
red.turnOn(true);
JPanel p1 = new JPanel(new GridLayout(3,1));
p1.add(red);
p1.add(yellow);
p1.add(green);
JPanel p2 = new JPanel(new FlowLayout());
p2.add(b1);
getContentPane().add(p1);
getContentPane().add(p2);
pack();
}
我知道必须有其他的if/else语句,但我不知道这是我应该去最好的方向
public void actionPerformed(ActionEvent e){
if (e.getSource() == b1){
green.turnOn(false);
yellow.turnOn(false);
red.turnOn(true);
}
}
完美我不知道你能够循环颜色,我应该能够使它现在工作。谢谢! – Liam