开发者

I want to implement a timer for a game java?

开发者 https://www.devze.com 2023-02-27 02:40 出处:网络
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?java.util.Timer is not a bad choice, but javax.swing.Timer may be

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?


java.util.Timer is not a bad choice, but javax.swing.Timer may be more convenient, as seen in this example.


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

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

The runnable describes what you want to do. For example:

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


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.

  • java timer for game
  • How to solve this Timer issue in java?
  • Timing and Animation in Java


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

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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消