Reshad
Reshad

Reputation: 2652

toggle a variable to true/false with a JButton

Hello I would like to know. How can I set a variable to true or false and vice versa with a JButton? My first thought would be create the variables like

private boolean value1, value2;

and the buttons like

private JButton toggle1, toggle2;

// see code below

The problem is that it won't react on the button somehow. Is it possible this way or do I have to use something else?

edit: here is the relevant code. ( my ActionListener)

    public void actionPerformed(ActionEvent e) {

    if( e.getSource() == toggle1 ) {

        if(aan1 == false) {

            aan1 ^= true;
            System.out.println(aan1);

        }
        else if(aan1 == true) {

            aan1 ^= false;
        }

    }

    try {
        // controleer of de ingevulde waarde tussen de 0 en de 15 is
        if( e.getSource() == burn && Integer.parseInt(textfield.getText()) < 16 && Integer.parseInt(textfield.getText()) > 0) {
            // brand kaars
            if( height > 15 && aan1 == true) {

                int aantal = Integer.parseInt(textfield.getText());
                height -= aantal;
            }


            if( height2 > 15 && aan2 == true) {
                int aantal = Integer.parseInt(textfield.getText());
                height2 -= aantal;
            }

            // opnieuw tekenen
            repaint();

        }
        else {

            JOptionPane.showMessageDialog(null, "error: vul een getal tussen de 0 en 15 in!"); // alertbox melding

        }
    }
    catch(NumberFormatException error) {

        JOptionPane.showMessageDialog(null, "error: een van de velden bevat geen cijfer of is niet ingevuld!"); // alertbox melding

    }

}

Upvotes: 0

Views: 4017

Answers (4)

Nicholas
Nicholas

Reputation: 5520

just do this?:

value1 != value1;

this inverst the current value: so if false, it will change to true, and vice versa.

EDIT: Should be:

value = !value;

Upvotes: 1

trashgod
trashgod

Reputation: 205875

As suggested in How to Use Buttons, JToggleButton may be a good choice for this, as the isSelected() predicate reflects the button's state.

state = button.isSelected()

Examples may be found here, here and here.

Upvotes: 2

icza
icza

Reputation: 418575

If you want to toggle a boolean variable when pressing a button, you should use a JCheckBox instead of JButton for that purpose which has an internal boolean state and it updates this variable on its own. The check box also makes this boolean state visible to the user.

When you need the boolean variable, you can ask it with the JCheckBox.isSelected() method.

Upvotes: 0

aws
aws

Reputation: 146

Not sure exactly what you're asking but to toggle the value of a boolean you can use:

value1 = !value1;

or

value1 ^= true;

Then print your variable:

System.out.println(value1);

Upvotes: 2

Related Questions