简体   繁体   English

将变量传递给Java ActionListener?

[英]Passing variables into a Java ActionListener?

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. 我想在某种定时方式中使用这两点...我尝试了Thread.sleep(),但是由于某种原因,它与程序的其余部分不能很好地结合在一起。 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();}

You could do this, which avoids declaring the parameters as final. 您可以这样做,避免将参数声明为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. 或者,您可以更改currentwanted的类型,以便它们是可变的Point持有人,并让actionPerformed方法查看这些持有人中的当前值。

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. 但是没有办法声明内部类,以便它可以看到对方法范围内的变量所做的更改……如果您要这样做的话。

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? 但是,仅将它们标记为“最终”有什么问题?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM