java - The final local variable cannot be assigned, since it is defined in an enclosing type -


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 write above code eclipse tells me this:

cannot refer non-final variable vote inside inner class defined in different method

but if add final before int vote gives me error:

the final local variable vote cannot assigned, since defined in enclosing type

so, how solve?

well, standard trick use int array of length one. make var final , write var[0]. important make sure don't create data race. using code example:

final int[] vote = {0};  class slidermoved implements changelistener {   public void statechanged(changeevent e) {     vote[0] = ratings.getvalue();   } } 

since happenenig on edt, including callback invocation, should safe. should consider using anonymous class:

ratings.addchangelistener(new changelistener() {   public void statechanged(changeevent e) { vote[0] = ratings.getvalue(); } }); 

Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -