我想为游戏 java 实现一个计时器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5710911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 12:25:19  来源:igfitidea点击:

I want to implement a timer for a game java?

javatimer

提问by Technupe

I want to have a method startTimer(30)where the parameter is the amount of seconds to countdown. How do I do so in Java?

我想要一个方法startTimer(30),其中参数是倒计时的秒数。我如何在 Java 中这样做?

采纳答案by sjr

The Java 5 way of doing this would be something like:

Java 5 的做法是这样的:

void startTimer(int delaySeconds) {
  Executors.newSingleThreadScheduledExecutor().schedule(
    runnable,
    delaySeconds,
    TimeUnit.SECONDS);
}

The runnabledescribes what you want to do. For example:

runnable描述你想要做什么。例如:

Runnable runnable = new Runnable() {
  @Override public void run() {
    System.out.println("Hello, world!");
  }
}

回答by trashgod

java.util.Timeris not a bad choice, but javax.swing.Timermay be more convenient, as seen in this example.

java.util.Timer不是一个糟糕的选择,但javax.swing.Timer可能更方便,如本例所示

回答by sgokhales

import java.awt.*;
import java.util.Timer;
import java.util.TimerTask;

public class TimerDemo {
  Toolkit toolkit;

  Timer timer;

  public TimerDemo(int seconds) {
    toolkit = Toolkit.getDefaultToolkit();
    timer = new Timer();
    timer.schedule(new RemindTask(), seconds * 1000);
  }

  class RemindTask extends TimerTask {
    public void run() {
      System.out.println("Time's up!");
      toolkit.beep();
      System.exit(0); 
    }
  }

  public static void main(String args[]) {
    System.out.println("About to schedule task.");
    new TimerDemo(30);
    System.out.println("Task scheduled.");
  }
}  

Many helpful links out there.

那里有许多有用的链接。

回答by ParisaN

Helping presented solution by "Javascript is GOD", I do this, play a game at a specific time.

通过“Javascript is GOD”帮助提出的解决方案,我这样做,在特定时间玩游戏。

public static void main(String args[]) {
  boolean flag = true;
  while (flag) {
      new TimerDemo(30);
      game();
    }
}

Notice that the flag variable changes within the game().

请注意,标志变量在game().