Creating a timer in java - java

I try to create a timer in java and show it on JFrame but when I comper my timer to my phone timer the timer in my phone is faster then my why?
I set the deley to 10 to every hundred of second in my timer.
This is the code only for the timer:
import javax.swing.Timer;
int min = 0, sec = 0, hundredSec = 0;
timer = new Timer(10, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
hundredSec++;
if(hundredSec >= 99)
{
sec++;
hundredSec = 0;
}
if(sec >= 59)
{
min++;
sec = 0;
}
timerL.setText(String.format("%02d:%02d:%02d", min, sec, millisec));
}
});
Sorry for bad english.
Thanks in advance for answer.

I believe that your problem has to do with the third line of code. As the java API docs says: "The delay parameter is used to set both the initial delay and the delay between event firing, in milliseconds." This means that there is a 10 millisecond delay every time, which might be causing your delay. To fix that you can change the line of code to:
timer = new Timer(0, new ActionListener());
By changing 10 to 0 it would run instantly as opposed to slowly falling behind. I would recommend reading this article to learn more about timers.

The delay you pass into a Timer is just that, a delay before the event is queued, not an exact time that the event will perform. While you can be sure that 10ms have passed since the last time the call was performed, you can't be sure that ONLY 10ms have passed.
You probably want something like this (with as little change to your code as possible; there are certainly different/more optimal ways to do this):
import javax.swing.Timer;
Date dt = new Date();
timer = new Timer(10, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int min = 0, sec = 0, hundredSec = 0;
long millisec = (new Date()).getTime() - dt.getTime();
hundredSec = ( millisec / 10 ) % 100;
sec = ( millisec / 1000 ) % 60;
min = ( millisec / 60000 );
timerL.setText(String.format("%02d:%02d:%02d", min, sec, hundredSec));
}
});
There are a couple issues here (missing timerL declaration, and I fixed the millisec reference in the setText call), but they're the same as you had above, so I assume you're just posting a snippet.

Related

How to add time events in libgdx

I wanted to know how can I add time to my events in libgdx. I have a button and when you press it a sprite will appear. I want the sprite to appear for only a short period of time. How can I do this? I used Scene2D to make the sprites as an actor.
I will show you an example in pseudo code.
wait time = 5 second;
current time = get time;
if (current time > wait time) {
// do the following
}
There's two ways to do this. You can either use something similar to your your pseudo code or you can use a timer.
Manual calculation:
private Long lifeTime;
private Long delay = 2000L; //1000 milliseconds per second, so 2 seconds.
public void create () {
lifeTime = System.currentTimeMillis();
}
public void render () {
lifeTime += Gdx.graphics.getDeltaTime();
if (lifetime > delay) {
//Do something
}
}
Using a timer:
private float delay = 2; //In seconds this time
//At some point you set the timer
Timer.schedule(new Task(){
#Override
public void run() {
// Do something
}
}, delay);
Read more here: https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/utils/Timer.html

Interval when using TimerTask in conjunction with Timer is not working

I am using timer.schedule(minuteTask, 0, 1000*60) to generate a new color at regular intervals. As you can see by the gif below that I recorded, the interval does not seem to be working.
Timer timer = new Timer ();
TimerTask minuteTask = new TimerTask() {
#Override
public void run () {
java.util.Random random = new java.util.Random();
int r = random.nextInt(255);
int g = random.nextInt(255);
int b = random.nextInt(255);
}
};
timer.schedule(minuteTask, 0, 1000*60);
Any idea on how to fix this?
Use this
new Timer().scheduleAtFixedRate(
new TimerTask() {
#Override
public void run() {
//put UR code herr
}
}, 0, 1000);
Hi I think you should use the scheduleAtFixedRate(..) function of Timer. This will help you to change the color in given time interval.
A simple schedule() method will execute at once while scheduleAtFixedRate() method takes and extra parameter which is for repetition of the task again & again on specific time interval.
Look at below code snippet:
Timer timer = new Timer();
timer.schedule( new performClass(), 30000 );
This is going to perform once after the 30 Second Time Period Interval is over. A kind of timeoput-action.
Timer timer = new Timer();
//timer.scheduleAtFixedRate(task, delay, period);
timer.scheduleAtFixedRate( new performClass(), 1000, 30000 );
This is going to start after 1 second and will repeat on every 30 seconds time interval.

Calculate FPS in Java Game [duplicate]

This question already has answers here:
Calculating frames per second in a game
(21 answers)
Closed 9 years ago.
Yesterday I wrote a Thread addressing how my game loop ran (in java) and how it works.
My game loop works completely, and I know why, but now I just wan't to know how to calculate FPS (Frames Per Second) and print it out every second.
I got a response yesterday about this, but he/she explained it in words and I couldn't understand it.
If anyone could help me (with a code example? :D) that would be great.
Here is my game loop:
while (running) {
start = System.nanoTime();
update();
draw();
drawToScreen();
elapsed = System.nanoTime() - start;
wait = targetTime - elapsed / 1000000;
if (wait < 0) {
wait = 5;
}
try {
Thread.sleep(wait);
} catch (Exception e) {
Game.logger.log("ERROR! Printing Stacktrace...");
e.printStackTrace();
}
}
ALSO:
In my JFrame when ever I call setName(string) it never works/updates on the Frame - Link me to a thread?
The easiest way to do this is to keep a variable whatTheLastTimeWas stored and doing this where you want to check your frame rate:
double fps = 1000000.0 / (lastTime - (lastTime = System.nanoTime())); //This way, lastTime is assigned and used at the same time.
Alternatively, you can make a FPS counter like so:
class FPSCounter extends Thread{
private long lastTime;
private double fps; //could be int or long for integer values
public void run(){
while (true){//lazy me, add a condition for an finishable thread
lastTime = System.nanoTime();
try{
Thread.sleep(1000); // longer than one frame
}
catch (InterruptedException e){
}
fps = 1000000000.0 / (System.nanoTime() - lastTime); //one second(nano) divided by amount of time it takes for one frame to finish
lastTime = System.nanoTime();
}
}
public double fps(){
return fps;
}
}
Then in your game, have an instance of FPSCounter and call nameOfInstance.interrupt(); when one frame is finished.
You can combine a simple counter and Timer.scheduleAtFixedRate for this.
Disclaimer: I don't know if this is the best method; it's just easy.
int totalFrameCount = 0;
TimerTask updateFPS = new TimerTask() {
public void run() {
// display current totalFrameCount - previous,
// OR
// display current totalFrameCount, then set
totalFrameCount = 0;
}
}
Timer t = new Timer();
t.scheduleAtFixedRate(updateFPS, 1000, 1000);
while (running) {
// your code
totalFrameCount++;
}

How to create a Timer that goes backwards

I'm making a Software by Java (& Netbeans IDE) and one of the features I would like to add is a timer that can be given a certain time (1 hour) and then let it run backwards till it goes 00:00:00 where it will do a certain action.
I tried to do something with my knowledge of adding a clock to the program but it didn't work. Please help
You could try this:
import java.util.Timer;
import java.util.TimerTask;
public class CountDown {
Timer timer;
public CountDown() {
timer = new Timer();
timer.schedule(new DisplayCountdown(), 0, 1000);
}
class DisplayCountdown extends TimerTask {
int seconds = 60;
public void run() {
if (seconds > 0) {
System.out.println(seconds + " seconds remaining");
seconds--;
} else {
System.out.println("Countdown finished");
System.exit(0);
}
}
}
public static void main(String args[]) {
System.out.println("Countdown Beginning");
new CountDown();
}
}
Read more: http://www.ehow.com/how_8675868_countdown-tutorial-java.html#ixzz2guYw8c99
I would start a new Thread where it waits 100 milliseconds (Thread.sleep(1000)) and then subtract that from hours * 60 /or minutes/ * 60 /* or seconds */ * 1000. If the result == 0 then you've hit that time.
Do you need to continuously display the countdown? If so, check this out: Java swing timer not decrementing the right way and not starting at the correct hour
If not, just use javax.Swing.Timer and set it for non-repeat and 3600 * 1000 millis
Edit: if you are not using Swing, then perhaps java.util.Timer

In Java, how do I execute code every X seconds?

I'm making a really simple snake game, and I have an object called Apple which I want to move to a random position every X seconds. So my question is, what is the easiest way to execute this code every X seconds?
apple.x = rg.nextInt(470);
apple.y = rg.nextInt(470);
Thanks.
Edit:
Well do have a timer already like this:
Timer t = new Timer(10,this);
t.start();
What it does is draw my graphic elements when the game is started, it runs this code:
#Override
public void actionPerformed(ActionEvent arg0) {
Graphics g = this.getGraphics();
Graphics e = this.getGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
e.fillRect(0, 0, this.getWidth(), this.getHeight());
ep.drawApple(e);
se.drawMe(g);
I would use an executor
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
Runnable toRun = new Runnable() {
public void run() {
System.out.println("your code...");
}
};
ScheduledFuture<?> handle = scheduler.scheduleAtFixedRate(toRun, 1, 1, TimeUnit.SECONDS);
Use a timer:
Timer timer = new Timer();
int begin = 1000; //timer starts after 1 second.
int timeinterval = 10 * 1000; //timer executes every 10 seconds.
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//This code is executed at every interval defined by timeinterval (eg 10 seconds)
//And starts after x milliseconds defined by begin.
}
},begin, timeinterval);
Documentation: Oracle documentation Timer
Simplest thing is to use sleep.
apple.x = rg.nextInt(470);
apple.y = rg.nextInt(470);
Thread.sleep(1000);
Run the above code in loop.
This will give you an approximate(may not be exact) one second delay.
You should have some sort of game loop which is responsible for processing the game. You can trigger code to be executed within this loop every x milliseconds like so:
while(gameLoopRunning) {
if((System.currentTimeMillis() - lastExecution) >= 1000) {
// Code to move apple goes here.
lastExecution = System.currentTimeMillis();
}
}
In this example, the condition in the if statement would evaluate to true every 1000 milliseconds.

Categories

Resources