for(int j=0;j<4;j++) { answerButtons[j].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { i++; next.setEnabled(true); if (answerButtons[j].getText().equals(rightanswer)) { right++; score.setText(right + "/" + i); show.setText("correct!"); answerButtons[j].setBackground(Color.green); } else { show.setText("wrong"); score.setText(right + "/" + i); answerButtons[j].setBackground(Color.pink); } rightanswer = getAnswer(i); enabled(false); next.setEnabled(true); } });}错在哪了
时间: 2024-01-17 15:05:25 浏览: 25
这段代码中存在一个常见的陷阱:在循环内部创建 ActionListener 时,由于闭包特性,所有的 ActionListener 都将共享相同的变量 j,这将导致 ActionEvent 事件中使用的 j 变量总是等于循环结束时的最终值,而不是期望的当前值。
为了避免这个问题,你需要使用一个 final 变量来保存循环变量的值,例如:
```
for (int j = 0; j < 4; j++) {
final int index = j;
answerButtons[index].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
i++;
next.setEnabled(true);
if (answerButtons[index].getText().equals(rightanswer)) {
right++;
score.setText(right + "/" + i);
show.setText("correct!");
answerButtons[index].setBackground(Color.green);
} else {
show.setText("wrong");
score.setText(right + "/" + i);
answerButtons[index].setBackground(Color.pink);
}
rightanswer = getAnswer(i);
enabled(false);
next.setEnabled(true);
}
});
}
```
在这个版本的代码中,我们创建了一个 final 变量 index 来保存循环变量 j 的值,并在 ActionListener 中使用它来访问 answerButtons 数组的元素。这样,每个 ActionListener 都会使用它自己的 index 值,而不会受到循环变量的影响。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)