获取javax swing计时器值

时间:2018-05-18 15:37:35

标签: java swing timer

我试图编写一个游戏,我输出玩家活着的时间(以毫秒为单位)。我以为我可以使用计时器并轻松获得它的价值。

public class InvaderPanel extends JPanel implements KeyListener,ActionListener {

private int timealive; //in ms, max value 2147483647 --->3.5 weeks
private Timer timer=new Timer(30,this); //I think it(30) should be 1 right ?
/**
 * Create the panel.
 */
  public InvaderPanel() {
    addKeyListener(this);
    setFocusable(true);
    timer.start();
  }

@Override
public void actionPerformed(ActionEvent e) {
if(playerdead){
    timer.stop;
    timealive=timer.value; // <--- That's what I'm looking for.
    }
}
}

但这就是我的问题:timer.value不存在,那么如何以毫秒为单位获取计时器的值?

1 个答案:

答案 0 :(得分:1)

这是我的解决方案。您需要创建每秒精确计时1次的计时器。当玩家还活着时,每次勾选都会增加timealive变量的值。我有另一个解决方案,但我认为这应该足够了。

public class InvaderPanel extends JPanel implements KeyListener,ActionListener {

  private int timealive; //in ms, max value 2147483647 --->3.5 weeks
  private Timer timer=new Timer(1000,this); // 1000ms = 1 second, but you 
                                            // can also set it to 30ms.
  /**
   * Create the panel.
   */
  public InvaderPanel() {
    addKeyListener(this);
    setFocusable(true);
    timer.start();
  }

  @Override
  public void actionPerformed(ActionEvent e) {
    if(playerdead){
      timer.stop();
      // here we can use timealive value
    } else {
      // timealive++; if you want to get the value in seconds
      //              in this case the timer delay must be 1000ms                  
      timealive += timer.getDelay(); // if you want to get the value in milliseconds
  }
}