ActionPerformed 在 Java 中运行不佳

ActionPerformed not working well in 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();
        }     
    }

}

您的问题是,您正在测试一个对象与其自身的相等性,这将永远为真...

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();
    }
}