简体   繁体   English

JButton切换方法无法正常工作

[英]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 . 这是我要尝试的操作:创建一个JButton ,单击该按钮时,其setText()将更改为Happy ,然后再次单击该按钮时,其setText()将更改为Sad Basically, I want it to toggle between Happy and Sad when clicked. 基本上,我希望它在单击时在“ Happy和“ Sad之间切换。 (Sorry for the awful explanation) (不好意思的解释)

The issue is that the button changes text only the first time I click it (from Happy to Sad ). 问题是该按钮仅在我一次单击时(从HappySad )更改文本。 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: 然后,我有我的ActionListener:

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

button.addActionListener (new ButtonListener());

You're assigning values to toggleButton in your if statements. 您正在为if语句中的toggleButton分配值。 Please use == or, better yet, if (toggleButton) and if (!toggleButton) . 请使用==或者更好的是if (toggleButton)if (!toggleButton) And why do you need else if for boolean anyway? 为什么你需要else if布尔呢?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM