Java - 如何在事件监听器中更改 'local?' 变量

标签 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";
    }
   }
};

最佳答案

你不能。

考虑一下:

  • 只要声明的方法运行,局部变量就存在。
  • 一旦该方法调用结束(通常是因为该方法存在),变量就会消失
  • 听众可以(而且通常确实)活得更久

那么当方法已经返回并且监听器试图修改局部变量时会发生什么?

因为这个问题没有很好的答案,他们决定通过不允许访问非 final 局部变量来使这种情况成为不可能。

解决这个问题有两种方法:

  • 尝试更改字段而不是局部变量(这可能也更适合监听器的生命周期)
  • 使用 final 局部变量,您可以更改其内容(例如 ListString[] 与单个元素)。

关于Java - 如何在事件监听器中更改 'local?' 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14382064/

相关文章:

mysql - 如何将 shell 命令的结果分配给 MySQL 变量?

javascript - event.preventDefault() 与返回 false

r - R 控制台能否支持后台任务或中断(事件处理)?

java - 如何在 Gradle Java 库项目构建脚本中指定 buildConfigField

java - 使用 eclipse microprofile-config 自定义配置文件

c# - 网站中静态变量的奇怪行为

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

html - 在 react 中添加范围的 mouseup 事件

java - 我不能在 GWT Collections.unmodifiableList(List l) 中使用来使我的列表只可读,因为不是可序列化的替代方法吗?

java - 安卓 : No resource identifier found for attribute 'headerView'