2016-01-20 75 views
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(); 
     }  
    } 

} 
+1

任何你使用AWT的原因(API取代16年以上),而不是Swing? – MadProgrammer

+1

'if(red == red){' - 你覺得這個不會是'true'嗎? – MadProgrammer

+0

@MadProgrammer你讓我有一個很好的問題。得到它了。謝謝。 –

回答

1

你的問題是,你正在測試與自身的目標,這將永遠是真正的平等......

if (red == red) { 

我認爲你想要更多的東西...

@Override 
public void actionPerformed(ActionEvent event) { 
    if (event.getSource() == button) { 
     if (red == Color.RED) { 
      red = Color.BLACK; 
      yellow = Color.YELLOW; 
     } else if (yellow == Color.YELLOW) { 
      yellow = Color.BLACK; 
      orange = Color.ORANGE; 
     } 
     repaint(); 
    } 
}