Question

Is there a way for me to pass variables into an actionlistener without calling them as final? I'd like to use these two points inside some sort of timed way... I tried Thread.sleep() but for some reason it doesn't mesh well with the rest of the program. This is the format I'd really like to use, but I'm aware it might be impossible to make it work. I'm open to any and all advice. Thanks!

(I'm sorry if this is a stupid question, I've looked for an answer but just can't seem to find one.)

public void timedMain(Point current, Point wanted){
          ActionListener taskPerformer = new ActionListener(){
              public void actionPerformed(ActionEvent evt){
                  System.out.println(wanted+" "+current);}};
                  actiontimer = new Timer(delay, taskPerformer);
                  actiontimer.start();}
Was it helpful?

Solution

You could do this, which avoids declaring the parameters as final.

public void timedMain(Point current, Point wanted) {
      final Point c = current;
      final Point w = wanted;
      ActionListener taskPerformer = new ActionListener(){
          public void actionPerformed(ActionEvent evt){
              System.out.println(w + " " + c);}};
              actiontimer = new Timer(delay, taskPerformer);
              actiontimer.start();}

Or you could change the types of current and wanted so that they were mutable Point holders, and have the actionPerformed method look at the current values in the holders.

But there is no way to declare the inner class so that it can see changes made to a variable in an enclosing method scope ... if that is what you are trying to do.

OTHER TIPS

You could do a few things

  • you could promote the anonymous action listener to a (private static) inner class, and pass the arguments to the constructor

  • you could define a function that built an anonymous action listener, rather than inline it in your code, and make the parameters to that function final

What's wrong with just marking them 'final', though?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top