Java - How to change a #39;local?#39; variable within an event listener(Java - 如何更改“本地?事件侦听器中的变量)
问题描述
有个小问题,希望有人能回答.基本上我有一个字符串变量,它需要根据组合框中的值进行更改,该组合框中附加了一个事件侦听器.但是,如果我将字符串设为 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[]
使用单个元素).
- try to change a field instead of a local variable (this probably also fits better with the life-time of the listener) or
- use a
final
local variable, of which you can change the content (for example aList
or aString[]
with a single element).
这篇关于Java - 如何更改“本地"?事件侦听器中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java - 如何更改“本地"?事件侦听器中的变量
基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01