java - 从一个 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。
解决方案
submit.addActionListener(this);
不要在 actionPerformed() 方法中添加 ActionListener。
每次调用 actionPerformed 时,您都会添加另一个侦听器,因此当您单击“提交”按钮时,您会获得多次执行的代码。
推荐阅读
- python - 在现有的 Chrome 浏览器窗口上运行 Selenium
- sql - 选择更新数据的 ID 哪个更好:使用 Temp 表加入或使用 OUTPUT INTO?
- android - Leanback 设置控制器可见性
- python - 如何创建自己的数据框?
- javascript - 理解视差滚动效果 - Javascript
- javascript - 为什么我的嵌套 setTimeout 延迟不起作用?
- mysql - 子查询计数条目数
- python - 不允许使用 Keras MaxPooling3D
- assembly - Dll 和组装
- java - 当我们在 LinkedList 中只有一个元素时,它不应该给出一些错误,因为我们试图使用 previous() 访问前一个索引