当我再次点击它时,我怎样才能改回 JButton 的原始颜色?

how can i change back the original color of JButton when i clicked it again?

下面的代码是我如何将 JButton 颜色更改为洋红色。我想做的是,当我再次单击同一个按钮时,我希望它恢复到正常颜色。我试过在 google 中搜索,但我似乎找不到这个问题的正确答案。如果你们有任何建议,请告诉我。谢谢。

    Object source = e.getSource();
    int s=0;

    if (source instanceof Component) {
        ((Component)source).setBackground(Color.magenta);
        s=0;

    }
    </i>
boolean switcher = false;
if (source instanceof Component) {
        if(switcher)((Component)source).setBackground(Color.OLDCOLOR);
        else ((Component)source).setBackground(Color.magenta);

        switcher = switcher?false:true;

    }

现在就看看颜色是什么:

if (((Component)source).getBackground().equals(Color.magenta)){
    ((Component)source).setBackground(null);
} else {
    ((Component)source).setBackground(Color.magenta);
    s=0;
}

null returns JButton 为默认颜色

为什么不实施自己的 JButton

public class MyButton extends JButton {

    private Color on;
    private Color off;
    private boolean isOn = false;

    public void setOnColor(Color on) {
        this.on = on;
    }

    public void setOffColor(Color off) {
        this.off = off;
    }

    public void switchColor() {
        if (this.isOn)
            super.setBackground(this.on);
        else
            super.setBackground(this.off);
        this.isOn = !this.isOn;
    }
} 

初始化按钮时

MyButton b = new MyButton();
b.setOffColor(null);
b.setOnColor(Color.MAGENTA);

如果你可以这样做

Object source = e.getSource();

if (source instanceof MyButton) {
    ((MyButton)source).switchColor();
}