gpt4 book ai didi

java - 将变量传递给 Java ActionListener?

转载 作者:行者123 更新时间:2023-11-30 06:36:52 24 4
gpt4 key购买 nike

有没有办法让我将变量传递给 actionlistener 而无需将它们称为 final?我想在某种定时方式中使用这两点...我尝试了 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();}

或者您可以更改 currentwanted 的类型,使它们成为可变的 Point 持有者,并让 actionPerformed 方法查看 holders 中的当前值。

但是没有办法声明内部类,以便它可以看到对封闭方法范围内的变量所做的更改......如果那是你正在尝试做的。

关于java - 将变量传递给 Java ActionListener?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4211823/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com