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

前端 未结 4 819
名媛妹妹
名媛妹妹 2021-02-05 11:19
ratingS = new JSlider(1, 5, 3); 
ratingS.setMajorTickSpacing(1);
ratingS.setPaintLabels(true);
int vote;

class SliderMoved implements ChangeListener {
    public void s         


        
4条回答
  •  野的像风
    2021-02-05 12:09

    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:

    final int[] vote = {0};
    
    class SliderMoved implements ChangeListener {
      public void stateChanged(ChangeEvent e) {
        vote[0] = ratingS.getValue();
      }
    }
    

    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:

    ratingS.addChangeListener(new ChangeListener() {
      public void stateChanged(ChangeEvent e) { vote[0] = ratingS.getValue(); }
    });
    

提交回复
热议问题