Rob*_*ook 4 java variables event-handling
有一个快速的问题,我希望有人可以回答.基本上我有一个String变量,需要根据组合框中的值进行更改,该组合框中附加了一个事件监听器.然而,如果我把弦变成最后那么它就不能改变,但是如果我不把它变成最终那么eclipse就会呻吟说它不是最终的.什么是最好的(也是最简单的)解决方案?
代码如下
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";
}
}
};
Run Code Online (Sandbox Code Playgroud)
你不能.
考虑一下:
那么当方法返回并且侦听器试图修改局部变量时会发生什么?
因为这个问题没有真正好的答案,所以他们决定不允许访问非final局部变量,从而使这种情况变得不可能.
有两种解决此问题的方法:
final局部变量,您可以在其中更改内容(例如a List或a String[]使用单个元素).