1
我有這個程序,當我點擊一個按鈕時,每次點擊它時顏色都會改變。我第一次點擊它會工作得很好。但是,當我再次點擊它不再工作。我缺少的東西在我的代碼繼承人我的代碼:?ActionPerformed在Java中運行不正常
public class TrafficLight extends Frame implements ActionListener{
protected Color red;
protected Color yellow;
protected Color orange;
Button button;
Panel panel;
public TrafficLight(){
red = Color.RED;
yellow = Color.BLACK;
orange = Color.BLACK;
button = new Button("Change Color");
add(button,BorderLayout.SOUTH);
button.addActionListener(this);
}
@Override
public void paint(Graphics graphics){
graphics.drawRect(200, 50, 100, 300);
graphics.setColor(red);
graphics.fillOval(200, 50, 100, 100);
graphics.setColor(yellow);
graphics.fillOval(200,150,100, 100);
graphics.setColor(orange);
graphics.fillOval(200,250,100, 100);
}
public static void main(String[] args) {
TrafficLight light = new TrafficLight();
light.setSize(500,500);
light.setTitle("Traffic Light");
light.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent event) {
System.out.print(yellow);
if(event.getSource() == button){
if(red == red){
red = Color.BLACK;
yellow = Color.YELLOW;
}
else if(yellow == yellow){
yellow = Color.BLACK;
orange = Color.ORANGE;
}
System.out.print(yellow);
repaint();
}
}
}
任何你使用AWT的原因(API取代16年以上),而不是Swing? – MadProgrammer
'if(red == red){' - 你覺得這個不會是'true'嗎? – MadProgrammer
@MadProgrammer你讓我有一個很好的問題。得到它了。謝謝。 –