我有一些定时器代码如下:
JLabel label = new JLabel();
JButton btnNewButton = new JButton("Stop Server after X Seconds");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int ans = functions.secC();
Timer t = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setText("Server will shutdown in: "+ans+ "seconds");
ans--;
}
});
t.start();
}
});
panel.add(btnNewButton);
panel.add(label);
在 ans--;
行我收到以下错误代码:
Local variable ans defined in an enclosing scope must be final or effectively final
我不确定应该做什么来修复这个错误,我已经尝试过将其最终确定,但这不起作用..
最佳答案
您可以将 ans
定义为 final
;
final int ans = functions.secC();
但是,如果其他地方不需要 ans
,您可以将其定义为 Timer
的实例字段;
Timer t = new Timer(1000, new ActionListener() {
private int ans = functions.secC();
public void actionPerformed(ActionEvent e) {
label.setText("Server will shutdown in: "+ans+ "seconds");
ans--;
}
});
但在这种情况下,我可能还会禁用该按钮,因为您实际上无法知道用户是否已经按下了该按钮...
关于java - int 表示计时器错误 : Local variable ans defined in an enclosing scope must be final or effectively final,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30682041/