java - 如何使 GUI 上的多个按钮同时工作

标签 java

我正在创建一个带有多个按钮的 GUI 程序。我目前只能使用其中一个按钮。这是我的按钮监听器类。我希望能够使用“测试”按钮,然后使用"is"或“否”按钮。如果您需要查看我的更多代码,请告诉我。

public class ButtonListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource()==TestButton)
        {

            TestWord = (Text_Input.getText());

            StringBuilder RevTestWord = new StringBuilder();
            RevTestWord.append(TestWord);
            RevTestWord = RevTestWord.reverse();

            DisplayText = "Is " + RevTestWord + " a real word?";    
            Test_Anadrome.setText(DisplayText);

            if(e.getSource()==YesButton)
            {
            DisplayText = "Word added to Anadrome list.";
            Test_Anadrome.setText(DisplayText);
            }

            if(e.getSource()==NoButton)
            {
                DisplayText = "Type a different word and press the 'Test Word' Button.";
                Test_Anadrome.setText(DisplayText);
            }

        }
    }
}

抱歉,我对 Java 还很陌生。

最佳答案

看起来 YesButtonNoButton 的 if/else 语句位于 TestButton 的 if 语句内,因此只有在 source==TestButton 时才会检查这些语句。尝试将此代码移到 if 语句之外:

            if(e.getSource()==YesButton)
            {
            DisplayText = "Word added to Anadrome list.";
            Test_Anadrome.setText(DisplayText);
            }

            if(e.getSource()==NoButton)
            {
                DisplayText = "Type a different word and press the 'Test Word' Button.";
                Test_Anadrome.setText(DisplayText);
            }

关于java - 如何使 GUI 上的多个按钮同时工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56283568/

相关文章:

java - 如何更新 JPanel 中的 JLabel?

java - 如何使用 apache-poi 或其他第三个库更改 ppt 演示模式?

java - 使用 @SecondaryTable 注释的 JPA/Hibernate 映射

java - 为什么我收到 JsonSyntaxException : Expected BEGIN_ARRAY but was STRING here?

java - 我想修复屏幕上 Java 程序启动的位置

java - 为什么我的 GregorianCalendar 对象返回错误的星期几?

java - 如何在JPA中保留父级和子级?

java - "no X11 display variable was set, but this program performs an operation which requires it"错误是什么意思以及如何/可以修复它?

java - Apache Storm : SLF4J: Class path contains multiple SLF4J bindings

java - 导入org.apache.commons.lang3无法解析