java - 获取javax swing计时器值

标签 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 次的计时器。当玩家还活着时,每个刻度都会增加 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
  }
}

关于java - 获取javax swing计时器值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50414854/

相关文章:

java - :Noob Alert: How can users in the same database add each other to their 'contact lists' ?

java - Kafka 流和窗口以在时间窗口内保持计数

c# - 如何使用带有 .NET Core 的 SignalR 从集线器类使用服务器端计时器?

swift - 我无法在 Swift 3 中使用计时器更改 label.text

java - 从 jmap 获取永久空间

java - 日期年份的 JPA 约束

java - 将 JLabel 的二维数组打印到 GridLayout

java - 从可执行 Jar 运行外部程序

java - 为什么用ConfirmDialog关闭Frme窗口会在两种情况下(确定和取消)关闭?

swift - 单元测试定时器?