user5327287
user5327287

Reputation: 410

Creating a timer in 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.

Upvotes: 1

Views: 310

Answers (2)

Spork
Spork

Reputation: 48

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.

Upvotes: 1

billjamesdev
billjamesdev

Reputation: 14642

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.

Upvotes: 0

Related Questions