繁体   English   中英

如何在TimerTask中停止对象?

[英]How stop object in TimerTask?

我在类GUI中有6个正在遍历代码的对象:

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

当某个物体到达某个点时,我要停止它。 在Anim类中,我正在做:

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秒后返回到起始位置。 我希望他一直睡在同一位置。

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应用程序的Swing应用程序中,请使用Swing Timer而不是Thread.sleep()Java Timer

了解更多如何使用Swing计时器

样例代码:

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();

编辑

请看看我的另一篇文章如何解决Java中的动画滞后?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM