无法分配最终的局部变量,因为它是在封闭类型中定义的

2022-09-03 04:18:48
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());

如果我写上面的代码Eclipse告诉我这个:

不能引用在其他方法中定义的内部类中的非最终变量投票

但是,如果我在int投票之前添加final,它会给我这个错误:

无法分配最终的局部变量投票,因为它是在封闭类型中定义的

那么,如何解决呢?


答案 1

好吧,标准的技巧是使用长度为一的int数组。使 var 成为最终变量并写入 。确保不会创建数据竞赛非常重要。以您的代码为例:var[0]

final int[] vote = {0};

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

由于所有这些都将在EDT上发生,包括回调调用,因此您应该是安全的。您还应该考虑使用匿名类:

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

答案 2

移至 :voteSliderMoved

class SliderMoved implements ChangeListener {
    private int vote;
    public void stateChanged(ChangeEvent e) {
        this.vote = ratingS.getValue();
        // do something with the vote, you can even access
        // methods and fields of the outer class
    }
    public int getVote() {
        return this.vote;
    }
}

SliderMoved sm = new SliderMoved();
ratingS.addChangeListener(sm);

// if you need access to the actual rating...
int value = rattingS.getValue();

// ...or
int value2 = sm.getVote();

编辑

或者,将模型类传递给更改侦听器

public class Person {
    private String name;
    private int vote;
    public int getVote() {
        return this.vote;
    }
    public void setVote(int vote) {
        this.vote = vote;
    }
    // omitting other setter and getter
}

Person使用方式如下:

 class SliderMoved implements ChangeListener {
    private Person person;
    public SliderMoved(Person person) {
        this.person = person;
    }
    public void stateChanged(ChangeEvent e) {
        this.person.setVote(ratingS.getValue());
    }
    public Person getPerson() {
        return this.person;
    }
}

Person person = new Person();

ratingS.addChangeListener(new SliderMoved(person));

// access the vote
int vote = person.getVote();

推荐