Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to implement a timer for a game java?

Tags:

java

timer

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?

like image 308
Technupe Avatar asked Jan 20 '23 23:01

Technupe


2 Answers

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

like image 133
trashgod Avatar answered Jan 22 '23 13:01

trashgod


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!");
  }
}
like image 38
sjr Avatar answered Jan 22 '23 14:01

sjr