the code below is how i change my JButton color to magenta. 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. 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
Why not implement your own 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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.