Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an on/off button on java?

I need a button that, when pressed, enables all the other buttons, and changes the name of a label from "Off" to "On", and when pressed again, disables all the buttons and turns the switch to "off" back again, like an on/off switch. The thing is, I can "turn it" on, but I can't turn it back off.

like image 603
Danilo Avatar asked May 17 '26 21:05

Danilo


2 Answers

If Swing, then perhaps you will want to place the buttons that you wish to control into an array or an ArrayList<AbstractButton>. That way the ActionListener of the control button can simply iterate through the array or the collection with a for loop, calling setEnabled(true) or false on the buttons. Consider making the controlling button be a JCheckBox or a JToggleButton.

Note, if you use a JToggleButton, then add an ItemListener to it. If you do so, there's no need to use booleans. Just check the state of the ItemEvent passed into the ItemListener's itemStateChanged method. If the getStateChanged() returns ItemEvent.SELECTED, then iterate through your JButton collection enabling all buttons. If it returns ItemEvent.DESELECTED, do the opposite.

Also note as per Byron Hawkins's comment:

You may want to consider that the ItemListener will receive events when the button is programmatically toggled, and also when the user toggles the button. The ActionListener only gets fired on input from the human user. I've often had bugs because I picked the wrong one.

like image 122
Hovercraft Full Of Eels Avatar answered May 19 '26 09:05

Hovercraft Full Of Eels


you'll need a boolean to represent the state of the button.

In other words, when your button is off (your boolean variable is false), from your onClick listener, you'll call a method "turnButtonOn()" or something of that nature.

If your boolean variable is true, then you'll call a method turnButtonOff()

public void onClick() {
    if(buttonOn){
      turnOff();
    }
    else {
      turnOn();
    }
    buttonOn = !buttonOn;
}
like image 40
amarunowski Avatar answered May 19 '26 09:05

amarunowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!