我需要一个Java计时器

时间:2014-02-21 12:54:41

标签: java swing timer

我的游戏需要一个计时器...... 我搜索了很多但没有运气。

请帮忙。

这是我的鼠标事件:

public void mouseClicked(MouseEvent e) {

     mouseX = e.getX();
     mouseY = e.getY();

     if(shot == false){
         Ink = 0;
     }

     if(ready == true){
     shot = true;   
         // I need a timer here to wait a second and then stop shooting.
     }

}

1 个答案:

答案 0 :(得分:3)

再次使用Swing Timer:

// code not compiled nor tested. It was typed free-hand.
// so it was not meant to be copy, pasted and used, but rather to show you 
// the idea.
public void mouseClicked(MouseEvent e) {
  mouseX = e.getX();
  mouseY = e.getY();

  // don't use if (shot == false). Instead do:
  if (!shot) {
     Ink = 0;
  }

  // likewise, no need to use if (ready == true). Instead do:
  if (ready) {
    shot = true;   

    // turn off your ability to shoot here by setting a boolean.
    ableToShoot = false;
    // start a Swing Timer that does not repeat
    // in the Timer turn back on the ability to shoot by setting a boolean
    Timer swingTimer = new Timer(TIMER_DELAY_TIME, new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        // allow shots here
        ableToShoot = true;
      }
    });
    swingTimer.setRepeats(false);
    swingTimer.start();   
  }
}

注意:

  • 除非您想让整个GUI进入休眠状态,否则不要使用Thread.sleep(...),因为这会睡眠Swing事件线程。
  • 不要使用java.util.Timer。 Swing的线程模型规定几乎所有的swing调用都是在Swing事件线程上进行的。 Swing Timer是为了做到这一点而构建的,以确保在EDT(Swing事件线程)上调用定时器中的所有调用。 java.util.Timer不会这样做,这将导致偶尔很难调试线程错误,这是最糟糕的错误。
  • The Swing Timer Tutorial link
  • The Swing event threading model tutorial link