首页 > 解决方案 > 从一个 ActionEvent 多次调用方法

问题描述

我正在尝试使用基于 ActionEvent 的按钮编写基于琐事的游戏。我在 if-else 结构中组织了每个连接到 JButton 实例的特定事件,并且在每个结构中,都会调用一个方法。其中一种方法会增加一个变量,该变量包含正确(cor)和错误(inc)答案的数量:

public void compare(String sel , String ans)

{

  //if correct
  if(sel.compareToIgnoreCase(ans) == 0)

    {

        q.setText("Correct! 10 points added!");
        score += 10;
        cor++;

    }

    //if incorrect
    else

    {

        q.setText("Incorrect! The correct answer was: " + ans);
       inc++;

    }

}

这组代码将从以下运行:

public void actionPerformed(ActionEvent event)

{

  if(e.equals("GUESS"))

  {

     userGuess = entry.getText();
     answer = ans.get(currentQuestionIndex);
     base.remove(entry);
     base.remove(submit);
     submit.setText("OK");
     submit.setActionCommand("OK");
     submit.addActionListener(this);
     base.add(submit);
     compare(userGuess, answer);

  } 

...

}

但是,每当调用 compare 方法时,inc 和 cor 值似乎都会增加一个不明确的值。例如,如果我正确回答一个问题,cor 的新值将是 2 而不是 1。当我回答另一问题时,cor 将是 5 而不是 2。我尝试在我的代码中使用跟踪器,但到目前为止,我似乎程序检测到运行 compare() 的 actionEvent 被多次按下,因此,它多次运行所述代码。如何修复我的代码,以便这些变量可以正确递增 1。

标签: javaswingawtjbuttonactionevent

解决方案


submit.addActionListener(this);

不要在 actionPerformed() 方法中添加 ActionListener。

每次调用 actionPerformed 时,您都会添加另一个侦听器,因此当您单击“提交”按钮时,您会获得多次执行的代码。


推荐阅读