user1123599
user1123599

Reputation:

Java Update JLabel in a loop

Sorry for posting yet another thread about Java swing and loops. I have read through others and none of the solutions have really been appropriate for me. Okay so now onto the problem. I have a class extending JFrame in which I have a Timer running a stopwatch as below:

class StopWatch extends TimerTask{
    public void run() {
        time.setText(String.format("%02d:%02d", minutes_elapsed,seconds_elapsed));
        seconds_elapsed++;
        if(seconds_elapsed == 60){
            seconds_elapsed = 0;
            minutes_elapsed++;
        }
    }

}

Now the only way my Label "time" updates is when I call time.update(time.getGraphics()) but this paints over the previous time. Any ideas what I should do? I have also tried repaint,validate,and paint. Paint does the same thing for me that update does...Any Ideas? P.S I don't know if it matters or not but I create the Timer in a public void start_timer() function which is like below:

public void start_timer(int minutes, int seconds){
        if(timer == null)
             timer = new Timer();
        timer.scheduleAtFixedRate(new StopWatch(),0,1000);
    }

Upvotes: 0

Views: 906

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500405

I suspect you're using a java.util.Timer instead of a javax.swing.Timer. The latter will make sure that the timer runs on the UI thread, which I suspect is the problem.

See "How to use Swing Timers" for a tutorial on them. You'll want to convert your TimerTask into an ActionListener`, and then use

timer.setDelay(1000);
timer.setRepeats(true);
timer.start();

Upvotes: 5

mre
mre

Reputation: 44240

You can do this

public void run() 
{
    SwingUtilities.invokeLater(new Runnable()
    {
        @Override
        public void run()
        {
            // do stuff
        }
    }
    ));
}

but you really should be using the javax.swing.Timer though. Remember that Swing is single-threaded and as such, its components must be modified in its thread (i.e. Event Dispatch Thread).

Upvotes: 4

Related Questions