java - int 表示计时器错误 : Local variable ans defined in an enclosing scope must be final or effectively final

标签 java swing variables local

我有一些定时器代码如下:

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/

相关文章:

java - 雨云:java.lang.ClassCastException:javax.swing.plaf.nimbus.DerivedColor$UIResource 无法转换为 javax.swing.Painter

javascript - 如何动态访问对象的属性?

java - 从菜单转发操作到父类

java - ECLIPSE - 使用 JNI 时出现 java.lang.UnsatisfiedLinkError

java - 如何使主窗口对表格单击使用react

java - 如何从 JTable 中删除一行?

Java EE/GlassFish - 线程和连接

java - 静态函数内局部变量的垃圾收集

Java - 外部变量声明

c# - 使用 C# 将完整结果集变量中的数据获取到脚本任务