Danilo
Danilo

Reputation: 93

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.

Upvotes: 2

Views: 18625

Answers (4)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285440

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.

Upvotes: 5

amarunowski
amarunowski

Reputation: 103

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;
}

Upvotes: 2

goravine
goravine

Reputation: 266

try use this simple code, use the variable as the flag

public int status = 0; //0 = on, 1=off

public void button_clicked()
{
    //on button clicked
    if(status == 0)
    {
        //logic here
        status = 1;
        buttonname.setText("Off");
    }
    //off button clicked
    else if(status == 1)
    {
        //logic here
        status = 0;
        buttonname.setText("On");
    }
}

Upvotes: 1

Byron Hawkins
Byron Hawkins

Reputation: 2705

If your button is pressed down and won't pop back up, chances are you have overridden a method in JToggleButton without calling super's version of it. Instead of overriding methods, create an ActionListener and use addActionListener() to attach to the button. When your listener is notified of button actions, check whether the toggle button is up or down and setEnabled() on the other buttons accordingly.

Upvotes: 1

Related Questions