int for timer error: Local variable ans defined in an enclosing scope must be final or effectively final

int for timer error: Local variable ans defined in an enclosing scope must be final or effectively final

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

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--;
    }
});  

但在这种情况下,我可能还会禁用按钮,因为你真的不知道用户是否已经按下按钮...