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.
Not tested, but I think this will work.
What's going on is that
ais 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 isfinalthen it's safe for Java to copy the value ofainto your inner class. However you need to modifyaso 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.