Java – countdown timer without GUI
Basically, I'm making a text-based "game" (not a game, but more a way to improve basic Java skills and logic) But as part of it, I want to have a timer It will reduce the time I want to go from variable to 0 Now, I've seen some ways to do this using GUI, but is there a way to do this without GUI / JFrame, etc
So what I want to know is You can count down from X to 0 without using GUI / JFrame If so, what would you do?
Thank you. Once I have some ideas, I will edit the progress
edit
// Start timer Runnable r = new TimerEg(gameLength); new Thread(r).start();
That's how I call threads / timers
public static void main(int count) {
If I have this in the timereg class, the timer matches But when I compile main in another thread
Now, I completely missed understanding threads and how this will work? Or is there something I miss?
Error:
constructor TimerEg in class TimerEg cannot be applied to given types; required: no arguments; found int; reason: actual and formal arguments differ in length
Online discovery runnable r = new timereg (gamelength);
Solution
Like the GUI, you use timer, but here you use Java util. Timer instead of swing timer Learn more about timer API Also, take a look at the TimerTask API, because you can use it with your timer
For example:
import java.util.Timer; import java.util.TimerTask; public class TimerEg { private static TimerTask myTask = null; public static void main(String[] args) { Timer timer = new Timer("My Timer",false); int count = 10; myTask = new MyTimerTask(count,new Runnable() { public void run() { System.exit(0); } }); long delay = 1000L; timer.scheduleAtFixedRate(myTask,delay,delay); } } class MyTimerTask extends TimerTask { private int count; private Runnable doWhenDone; public MyTimerTask(int count,Runnable doWhenDone) { this.count = count; this.doWhenDone = doWhenDone; } @Override public void run() { count--; System.out.println("Count is: " + count); if (count == 0) { cancel(); doWhenDone.run(); } } }