我試圖將交通燈由紅色變爲黃色並在綠色中重複,並通過按下一個按鈕來啓動此過程。這是我的代碼:更改交通燈狀態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