计算 jButton 数组中的点击次数
Counting clicks in a jButton array
我正在尝试计算一组按钮中的鼠标点击次数,但我的 "click" 变量出现一个我不太明白的错误:
"Local variable click defined in an enclosing scope must be final or effectively final"
我猜这与我如何安排 for 循环和 actionListener 有关。有人可以指导我正确的方向吗?谢谢
int click = 0;
JButton buttonArray1 [] = {a1, a2, a3, a4, b1, b2, b3, b4, c1, c2, c3, c4, d1, d2, d3, d4};
for (int d = 0; d < buttonArray1.length; d++) {
buttonArray1[d].addActionListener(new ActionListener() {
//add an action listener to the current button
@Override
public void actionPerformed(ActionEvent e)
{
click = click +1;
}
});
已解决:
class Click{
int counter = 0 ;
public void Click(){
counter++;
}
public int GetClick(){
return counter;
}
}
将 click 定义为 class 变量...
原因是actionPerformed是一个回调接口实现...
因此你有 2 个选择
- 使 click 最终(没有意义,因为那样你就不能改变它的值)
- 或将 click 声明为 class 变量...(这就是您的情况)
我正在尝试计算一组按钮中的鼠标点击次数,但我的 "click" 变量出现一个我不太明白的错误:
"Local variable click defined in an enclosing scope must be final or effectively final"
我猜这与我如何安排 for 循环和 actionListener 有关。有人可以指导我正确的方向吗?谢谢
int click = 0;
JButton buttonArray1 [] = {a1, a2, a3, a4, b1, b2, b3, b4, c1, c2, c3, c4, d1, d2, d3, d4};
for (int d = 0; d < buttonArray1.length; d++) {
buttonArray1[d].addActionListener(new ActionListener() {
//add an action listener to the current button
@Override
public void actionPerformed(ActionEvent e)
{
click = click +1;
}
});
已解决:
class Click{
int counter = 0 ;
public void Click(){
counter++;
}
public int GetClick(){
return counter;
}
}
将 click 定义为 class 变量...
原因是actionPerformed是一个回调接口实现...
因此你有 2 个选择
- 使 click 最终(没有意义,因为那样你就不能改变它的值)
- 或将 click 声明为 class 变量...(这就是您的情况)