将变量传递到 Java ActionListener 中?
-
25-09-2019 - |
题
有没有办法让我将变量传递到动作侦听器而不将它们称为最终变量?我想以某种定时方式使用这两点......我尝试了 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();}
解决方案
您可以做到这一点,这避免了声明的参数作为最终
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();}
或者你也可以改变类型current
和wanted
,使他们可变的Point
持有人,并有actionPerformed
方法看在持有人的当前值。
但有没有办法申报的内部类,以便它可以看到在一个封闭的方法,范围变量所做的更改......如果这是你正在尝试做的。
其他提示
你可以做一些事情
您可以将匿名操作侦听器提升为(私有静态)内部类,并将参数传递给构造函数
您可以定义一个构建匿名操作侦听器的函数,而不是将其内联到代码中,并将该函数的参数设置为最终参数
但是,仅仅将它们标记为“最终”有什么问题吗?
不隶属于 StackOverflow