简体   繁体   English

如何在n秒后停止摆动计时器?

[英]How can I stop a Swing Timer after n seconds?

I'm trying to make an image twinkle with RaffleImage(); 我试图用RaffleImage();制作一个图像闪烁RaffleImage(); while I'm executing the timer, my character is immune to any collision, I want it to be immune only for 2 seconds, so the timer get execute only for 2 seconds and then get finished. 当我正在执行计时器时,我的角色对任何碰撞都免疫,我希望它只能在2秒内免疫,所以计时器只执行2秒然后完成。

I've tried subtracting System.currentTimeMillis() but any variable I create from this method, have always the same value, making me get a zero from that subtracting. 我已经尝试减去System.currentTimeMillis()但是我从这个方法创建的任何变量总是具有相同的值,这使得我从减法中得到零。

Do you know how I can stop or pause the timer after any elapsed time in seconds? 你知道如何在经过几秒钟的时间后停止或暂停计时器吗?

immuneTimer = new Timer(50, new ActionListener() {  
        @Override
    public synchronized void actionPerformed(ActionEvent e) {
    long initMillis = System.currentTimeMillis();
     if (System.currentTimeMillis() - initMillis > 2000 ) { // this substract gives me 0
        initImages();
        setImmune(false); // so this never reached
        immuneTimer.stop();
      } else {
            raffleImage(); //its executing like forever;
             }
      }
});

The Swing timer fires a an ActionEvent . Swing计时器触发一个ActionEvent From the event you can use getSource() to get the source of the event. 从事件中,您可以使用getSource()来获取事件的来源。 Cast that source to the swing timer object and use that to turn it off. 将该源转换为swing计时器object并使用它来关闭它。

To know when to turn it off you need to have a variable count the number of times the swing timer is invoked. 要知道何时关闭它,您需要有一个变量count调用swing计时器的次数。 When the variable reaches that amount, turn it off. 当变量达到该量时,将其关闭。


int elapsedTime = 0;
int timerDelay = 50;
int max = 2000;
public void actionPerformed(ActionEvent ae) {
     elapsedTime += timerDelay; // you could use getDelay here but it
                                // is in milliseconds.
     if (elapsedTime >= max) {
        Timer s = (Timer)ae.getSource();
        s.stop();
     }
     // rest of code
}

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

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