Java-如何更改“本地"?事件监听器中的变量 [英] Java - How to change a 'local?' variable within an event listener

查看:52
本文介绍了Java-如何更改“本地"?事件监听器中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想回答一个简短的问题,希望有人能回答.基本上,我有一个String变量,需要根据组合框的值进行更改,该组合框具有附加的事件侦听器.但是,如果我将字符串定为final,则无法更改,但是如果我不将其定为final,则日食mo吟表示该字符串不是final.最好(最简单)的解决方法是什么?

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 a List or a String[] with a single element).

这篇关于Java-如何更改“本地"?事件监听器中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆