ActionPerformed在Java中运行不佳

时间:2016-01-20 05:28:36

标签: java awt

我有这个程序,当我点击一个按钮时,每次点击它时颜色都应该改变。我第一次点击它会很好。然而,当我再次点击它不再工作。我在代码中遗漏了哪些东西?继承我的代码:

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 个答案:

答案 0 :(得分: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();
    }
}