将变量传递到 Java ActionListener 中?
有没有办法让我将变量传递到动作侦听器而不将它们称为最终变量?我想以某种定时方式使用这两点...我尝试了 Thread.sleep() 但由于某种原因它与程序的其余部分不能很好地配合。这是我真正想使用的格式,但我知道它可能无法实现。 我愿意接受任何建议。谢谢!
(如果这是一个愚蠢的问题,我很抱歉,我一直在寻找答案,但似乎找不到答案。)
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();}
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();}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以这样做,这可以避免将参数声明为最终参数。
或者,您可以更改
current
和wanted
的类型,以便它们是可变的Point
持有者,并具有actionPerformed
方法查看持有者中的当前值。但是没有办法声明内部类,以便它可以看到对封闭方法范围内的变量所做的更改......如果这就是您想要做的。
You could do this, which avoids declaring the parameters as final.
Or you could change the types of
current
andwanted
so that they were mutablePoint
holders, and have theactionPerformed
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.
您可以做一些事情
您可以将匿名操作侦听器提升为(私有静态)内部类,并将参数传递给构造函数
您可以定义一个构建匿名操作侦听器的函数,而不是在代码中内联它,并将参数设置为该函数的最终参数
但是,仅将它们标记为“最终”有什么问题吗?
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?