Nick
Nick

Reputation: 61

JButton toggle method not working as expected

Here's what I'm trying to do: Create a JButton, and when clicked, its setText() will change to Happy, and then when clicked again, its setText() will change to Sad. Basically, I want it to toggle between Happy and Sad when clicked. (Sorry for the awful explanation)

The issue is that the button changes text only the first time I click it (from Happy to Sad). When clicked again, it does not change text.

This is my code for the toggle method:

boolean toggleButton = true;
JButton button = new JButton("Sad");

public void changeButtonText() {
    if(toggleButton = true) {
        toggleButton = false;
        button.setText("Happy");
    } else if (toggleButton = false) {
        toggleButton = true;
        button.setText("Sad");
    }
}

Then, I have my ActionListener:

class ButtonListener implements ActionListener {
    public void actionPerformed (ActionEvent event) {
        changeButtonText();
    }
}

button.addActionListener (new ButtonListener());

Upvotes: 1

Views: 144

Answers (1)

SqueezyMo
SqueezyMo

Reputation: 1726

You're assigning values to toggleButton in your if statements. Please use == or, better yet, if (toggleButton) and if (!toggleButton). And why do you need else if for boolean anyway?

public void changeButtonText() {
   toggleButton = !toggleButton;
   button.setText(toggleButton ? "Happy" : "Sad");
}

Upvotes: 8

Related Questions