ratingS = new JSlider(1, 5, 3);
ratingS.setMajorTickSpacing(1);
ratingS.setPaintLabels(true);
int vote;
class SliderMoved implements ChangeListener {
public void stateChanged(ChangeEvent e) {
vote = ratingS.getValue();
}
}
ratingS.addChangeListener(new SliderMoved());
If i write the above code Eclipse tells me this:
Cannot refer to a non-final variable vote inside an inner class defined in a different method
But if i add final before int vote it gives me this error:
The final local variable vote cannot be assigned, since it is defined in an enclosing type
So, how to solve?
Move
vote
toSliderMoved
:EDIT
Or alternatively, pass a model class to the change listener
Person
is used as follows:I finally solved declaring vote as instance variable (private) in the main class.
Setting the Compiler compliance level to 1.8 worked for me to solve a similar problem. I don't understand the reason but you may try this.
How it works:
Right click on the project --> Properties --> Java Compiler. And in java compiler properties window, set the compiler compliance level to 1.8.
Well, the standard trick is to use an int array of length one. Make the var final and write to
var[0]
. It is very important to make sure you don't create a data race. Using your code as an example:Since all this will be happenenig on the EDT, including the callback invocation, you should be safe. You should also consider using the anonymous class: