gpt4 book ai didi

java - 计时器在我的代码中无法正常工作

转载 作者:行者123 更新时间:2023-11-29 04:38:57 26 4
gpt4 key购买 nike

所以我正在制作的程序的计划是让一个物体从一个点移动到另一个点。问题是绘制了路径。我能够绘制并放置一个 shape 以从头到尾移动路径。我遇到的问题是对象出现在路径的末尾。即使在 for 循环 的末尾设置了 timer。它所做的只是简单地等待 timer 完成,然后形状就在路径的尽头。

我已经检查了代码,甚至打印出已存储的每个点,我得到了点,而不仅仅是最后一个点。对象的路径基于 for 循环遍历每个点并将对象放置在所述点。这是粗略的 atm 并使用绝对位置(仅针对对象)。

我错过了什么?

代码如下:

    JButton add = new JButton("add");
add(add);
//new Timer(50, updateTask).start();
updateTask = new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
repaint(); // Refresh the JFrame, callback paintComponent()
}
};

add.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
for (int i = 0; i < path.size(); i++) {
update(i); // update the (x, y) position
new Timer(1000, updateTask).start();
}
}
});
}

public void update(int i) {
if (released == 1) {
Point p = path.get(i);
System.out.println("position at: " + (int) p.getX() + " " + (int) p.getY());
xPos = (int) p.getX();
yPos = (int) p.getY();
System.out.println(i);
}
}

最佳答案

您不能在 ActionListener 中编写循环,因为那样会阻塞 EventDispatchThread (EDT),从而阻塞您的 UI。

相反,您可以使用 updateTask ActionListener 在每次从 Timer 调用时逐步执行您的路径:

final Timer timer = new Timer(1000, null);
updateTask = new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
if (pathIndex < path.size()) {
update(pathIndex++);
} else {
timer.stop();
}
repaint(); // Refresh the JFrame, callback paintComponent()
}
};
timer.addActionListener(updateTask);

add.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
pathIndex = 0;
timer.start();
}
});

为此,您的类需要一个额外的 int 字段 pathIndex

关于java - 计时器在我的代码中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40061152/

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