Daksh Shah
Daksh Shah

Reputation: 3113

Local Variable Accessed from within - Java

I get a error in timer.stop(), it says that "local variable timer is accessed from within the class; needs to be declared 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);
        }
    });
}

I tried this:

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

And now the error comes on "final Timer timer = new Timer(1000, new ActionListener() {" that timer is already defined in main(java.lang.String[]) and if i remove Timer timer; it shows error on "timer.stop()" that variable timer might not have been initialised

Upvotes: 0

Views: 141

Answers (3)

RokL
RokL

Reputation: 2812

Another way is this:

In actionPerformed instead of timer.stop() write ((Timer)e.getSource()).stop();.

Upvotes: 1

Claudiu
Claudiu

Reputation: 1489

so the problem is you declare timer 2 times

Timer timer;

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

just delete the line:

Timer timer;

Upvotes: 0

RokL
RokL

Reputation: 2812

Try this:

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

Upvotes: 2

Related Questions