我正在创建一个带有多个按钮的 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 还很陌生。
最佳答案
看起来 YesButton
和 NoButton
的 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/