简体   繁体   English

再次单击时,如何更改JButton的原始颜色?

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

the code below is how i change my JButton color to magenta. 下面的代码是我如何将JButton颜色更改为洋红色。 what i wanted to do is when i click the same button again i want it to go back to its normal color. 我想要做的是当我再次单击相同的按钮时,我希望它恢复到其正常的颜色。 I've tried searching in google but i can't seem to find the right answer for this problem. 我曾尝试在Google中搜索,但似乎无法找到解决此问题的正确答案。 if you guys have any suggestion please let me know. 如果你们有任何建议,请告诉我。 thank you. 谢谢。

    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;

    }

Just check what's color right now: 只需检查一下现在的颜色:

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

null returns JButton to default color null将JButton返回默认颜色

Why not implement your own 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;
    }
} 

When initializing the button 初始化按钮时

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

In the event you can then do 万一您可以

Object source = e.getSource();

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM