从内部访问的局部变量 - Java

时间:2013-09-23 13:28:13

标签: java variables timer local

我在timer.stop()中遇到错误,它说“从类中访问本地变量计时器;需要声明为final”

public static void main(String args[]) {
    int tick; 
    Timer timer;


        timer = new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int tick=0;
                System.out.println("Success" + ++tick);
                if (tick > 4) {
                    timer.stop();
                }
            }
        });
        timer.setInitialDelay(0);







    java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
            new NewJFrame().setVisible(true);
        }
    });
}

我试过了:

public static void main(String args[]) {

    int tick; 
    Timer timer;


     final Timer timer = new Timer(1000, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        int tick=0;
        System.out.println("Success" + ++tick);
        if (tick > 4) {
            timer.stop(); //this refers to the final variable timer, this is valid.
        }
    }
          });
        timer.setInitialDelay(0);







    java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
            new NewJFrame().setVisible(true);
        }
    });
}

现在出现错误“最终定时器计时器=新计时器(1000,新的ActionListener(){”该计时器已在main(java.lang.String []中定义) 如果我删除定时器计时器;它在“timer.stop()”上显示错误,即变量计时器可能尚未初始化

3 个答案:

答案 0 :(得分:2)

试试这个:

public static void main(String[] args) {
    class Listener implements ActionListener {
        int tick = 0;
        Timer timer = null;
        public void setTimer(Timer timer) {
            this.timer = timer;
        }
        public void actionPerformed(ActionEvent e) {
            tick++;
            if (tick > 4) {
                timer.stop();
            }
        }
    }
    Listener listener = new Listener();
    Timer timer = new Timer(1000, listener);
    listener.setTimer(timer);
    timer.setInitialDelay(0);
}

答案 1 :(得分:1)

另一种方式是:

在actionPerformed而不是timer.stop()中写((Timer)e.getSource()).stop();

答案 2 :(得分:0)

所以问题是你宣告计时器2次

Timer timer;

final Timer timer = new Timer(1000, new ActionListener() {
...

只需删除该行:

Timer timer;