javanetbeansmouseeventtimertask

"local variables referenced from an inner class must be final or effectively final" in MouseEvent


I am trying to get the integer input from a jtextfield and set it as the integer for a timer jlabel when the jbutton is clicked but I keep getting this error inside the MouseEvent method

local variables referenced from an inner class must be final or effectively final

Code:

    private void timerStartMouseClicked(java.awt.event.MouseEvent evt) {                                        
        int a = Integer.parseInt(timerInput.getText());
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {         
            public void run() {  
                timeLeft.setText(Integer.toString(a));
                --a;
                if (a == -1){
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
                    timer.cancel();                                       
                } else if(isRunning){
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
                }
            }
        };
    timer.scheduleAtFixedRate(task, 1000, 1000);
    }

I am still new with Timer Events and Mouse Events, I tried to declare a as a global var which still gives me the same error unless I declare it a value within the method but I need to get the input from the jtextfield.


Solution

  • Not tested, but I think this will work.

        private void timerStartMouseClicked(java.awt.event.MouseEvent evt) {                                        
            final int a = Integer.parseInt(timerInput.getText());
            Timer timer = new Timer();
            TimerTask task = new TimerTask() {    
                int localCount = a;     
                public void run() {  
                    timeLeft.setText(Integer.toString(localCount));
                    --localCount;
                    if (localCount == -1){
    \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
                        timer.cancel();                                       
                    } else if(isRunning){
    \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
                    }
                }
            };
        timer.scheduleAtFixedRate(task, 1000, 1000);
      
    

    What's going on is that a is a local variable and is going to vanish into the ether when this method ends, therefore it's not safe to use. If the variable is final then it's safe for Java to copy the value of a into your inner class. However you need to modify a so a constant value won't work.

    So we just copy the value into a different variable, one inside the inner class. This makes everything work fine, because now the inner class has its own variable to work with.