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.
Share
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, callingsetEnabled(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: