有个小问题,希望有人能回答.基本上我有一个字符串变量,它需要根据组合框中的值进行更改,该组合框中附加了一个事件侦听器.但是,如果我将字符串设为 final,则无法更改,但如果我不将其设为 final,则 eclipse 会抱怨它不是最终的.最好(和最简单)的解决方法是什么?
Got a quick question which I hope someone can answer. Basically I have a String variable which needs changing based upon the value in a combo box which has an event listener attached to it. However if I make the string final then it cant be changed, but if i don't make it final then eclipse moans that it isn't final. Whats the best (and simplest) work around?
代码如下
final String dialogOutCome = "";
//create a listener for the combo box
Listener selection = new Listener() {
public void handleEvent(Event event) {
//get the value from the combo box
String comboVal = combo.getText();
switch (comboVal) {
case "A": dialogOutCome = "a";
case "B": dialogOutCome = "b";
case "C": dialogOutCome = "c";
case "D": dialogOutCome = "d";
}
}
};
你不能.
考虑一下:
那么当方法已经返回并且监听器尝试修改局部变量时会发生什么?
So what should happen when the method returned already and the listener tries to modify the local variable?
因为这个问题没有很好的答案,他们决定通过不允许访问非final
局部变量来使这种情况变得不可能.
Because this question does not have a really good answer, they decided to make that scenario impossible by not allowing access to non-final
local variables.
有两种方法可以解决这个问题:
There are two ways around this problem:
final
局部变量,您可以更改其中的 content(例如 List
或 String[]
使用单个元素).final
local variable, of which you can change the content (for example a List
or a String[]
with a single element).这篇关于Java - 如何更改“本地"?事件侦听器中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!