![](/img/trans.png)
[英]Java: the final local variable cannot be assigned, since it was defined in an enclosing type
[英]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());
如果我寫上面的代碼Eclipse告訴我這個:
不能在不同方法中定義的內部類中引用非最終變量vote
但如果我在int vote之前添加final ,它會給我這個錯誤:
無法分配最終的局部變量投票,因為它是在封閉類型中定義的
那么,如何解決?
好吧,標准技巧是使用長度為1的int數組。 使var final並寫入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(); }
});
將vote
移至SliderMoved
:
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();
我終於在主類中將聲明聲明為實例變量(私有)。
將編譯器合規性級別設置為1.8對我來說可以解決類似的問題。 我不明白原因,但你可以試試這個。
這個怎么運作:
右鍵單擊項目 - > Properties - > Java Compiler。 在java編譯器屬性窗口中,將編譯器合規性級別設置為1.8。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.