如何在 ActionListener 中初始化一个局部变量? - Java
How to initialize a local variable in ActionListener? - Java
如果我想在 ActionListener 中初始化局部变量,我会收到此错误:
Local variable word defined in an enclosing scope must be final or effectively final.
代码看起来像这样:
int number = 0;
anyButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
//And here I get the error:
number++;
}
});
你知道怎么做吗?
您需要一个可变的线程安全变量,而不是原始变量。
考虑用包装器 class(可以是您自己的包装器或标准包装器 [例如 AtomicInteger
])或单元素数组替换原语:
final AtomicInteger number = new AtomicInteger();
...
number.getAndIncrement();
如果我想在 ActionListener 中初始化局部变量,我会收到此错误:
Local variable word defined in an enclosing scope must be final or effectively final.
代码看起来像这样:
int number = 0;
anyButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
//And here I get the error:
number++;
}
});
你知道怎么做吗?
您需要一个可变的线程安全变量,而不是原始变量。
考虑用包装器 class(可以是您自己的包装器或标准包装器 [例如 AtomicInteger
])或单元素数组替换原语:
final AtomicInteger number = new AtomicInteger();
...
number.getAndIncrement();