Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to change a 'local?' variable within an event listener

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?

Code is as follows

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";
    }
   }
};
like image 762
Robert Flook Avatar asked Jan 14 '23 11:01

Robert Flook


1 Answers

You can't.

Consider this:

  • the local variable exists as long as the method it's declared in runs.
  • as soon as that method invocation ends (usually because the method exists) the variable vanishes
  • the listener can (and usually does) live much longer

So what should happen when the method returned already and the listener tries to modify the local variable?

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:

  • 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).
like image 58
Joachim Sauer Avatar answered Feb 04 '23 19:02

Joachim Sauer