当我再次单击JButton时,如何将其更改回原来的颜色



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

    Object source = e.getSource();
    int s=0;
    if (source instanceof Component) {
        ((Component)source).setBackground(Color.magenta);
        s=0;
    }
    </i>

现在只需检查颜色:

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

null将JButton返回到默认颜色

boolean switcher = false;
if (source instanceof Component) {
        if(switcher)((Component)source).setBackground(Color.OLDCOLOR);
        else ((Component)source).setBackground(Color.magenta);
        switcher = switcher?false:true;
    }

为什么不实现自己的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();
}

最新更新