Show a timer in a Java Frame

421 Views Asked by At

I want to show the elapsed time of a game i'm doing. Basically i want to call the class that keeps track of the score and with calling the class i want to start a timer that just continually runs and shows the elapsed time, this should be added.

Is there any way to do this without using System.Currenttime, i tried using that but it seems like there should be an easier way, since I don't really need a lot of precision, I just want it to start counting and close with the rest of the program.

1

There are 1 best solutions below

4
On BEST ANSWER

You can use this to create a timer:

timer = new Timer(speed, this);
timer.setInitialDelay(pause);
timer.start();

I would put 1000 in speed so that it updates every 1 second, (since the times goes my milliseconds.)

Next, I would create a label in your java program:

JLabel label = new JLabel("Text Here");
add(label);

Then, I would do this:

label.setText(timer.toString());

That is basically how you add a timer to a label on a JFrame. For more advanced methods, these websites might help:

https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html

http://www.javabeginner.com/java-jlabel-class-example/

How do you change label text in java after a timer ticks a second passed?

Please +1 this answer if it helped you! :)