gpt4 book ai didi

java - 如何停止TimerTask中的对象?

转载 作者:行者123 更新时间:2023-12-01 22:54:21 25 4
gpt4 key购买 nike

我在类 GUI 中有 6 个对象,它们正在通过代码移动:

Anim anim = new Anim();
Timer timer = new Timer();
timer.scheduleAtFixedRate(anim, 30, 30);

当一个物体到达某个点时我想阻止它。在动画课上我正在做:

public class Anim extends TimerTask {
@Override
public void run() {
if (t1.x == 300 && t1.y == 300) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

它停止了应用程序,我想停留在一个具体的对象上。怎么做?

编辑:

好的,现在可以正常使用了,不会干扰其他对象。但物体继续移动,1 秒后回到起始位置。我希望他 sleep 时一直处于同一个位置。

if (Main.auto1.x == 700 && Main.auto1.y == 350) {
timer = new javax.swing.Timer(1000, new ActionListener() {

@Override
public void actionPerformed(ActionEvent arg0) {
Main.auto1.x = 700;
Main.auto1.y = 350;
}
});
timer.setRepeats(false);
timer.start();

最佳答案

使用Swing Timer而不是 Thread.sleep() 和 Java Timer在 Swing 应用程序中,有时会挂起 Swing 应用程序。

了解更多 How to Use Swing Timers

示例代码:

private Timer timer;
...
timer = new javax.swing.Timer(3000, new ActionListener() {

@Override
public void actionPerformed(ActionEvent arg0) {

//do what ever you want to do
// call timer.stop() when the condition is matched

}
});
timer.setRepeats(true);
timer.start();
<小时/>

编辑

请看我的另一篇文章How to fix animation lags in Java?

关于java - 如何停止TimerTask中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24306564/

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