简体   繁体   中英

Real-time updating stopwatch in Java?

I'm trying to make a stopwatch that constantly updates to the screen what the time is. The time object is a JLabel that should display the time elapsed. I have everything imported and set up right, but whenever the start button is clicked to activate the timer, the program freezes.

public class Timing
{
    public void Timer()
    {
        startTime = System.currentTimeMillis();
        while(isTiming == true)
        {
            endTime = System.currentTimeMillis();
            elapsedTime = endTime - startTime;
            time.setText("" + elapsedTime);
            info.validate();
        }
        endTime = System.currentTimeMillis();
        elapsedTime = endTime - startTime;
        time.setText("" + elapsedTime);
        info.validate();
    }
}

Here's the Action Listener part:

public void actionPerformed(ActionEvent arg0)
{
if(((JButton) arg0.getSource()).getText().equals("Start"))
    {
        isTiming = true;
        new Timing().Timer();
    }

You are trying to synchronously update your label in a loop in the UI thread, the same thread which is used for applying UI updates. By doing this you are blocking the execution which results into the freeze you are describing.

To resolve this, you could use the javax.swing.Timer to schedule the updates so that they would be run in the same UI thread, but only when needed, ie

timer = new javax.swing.Timer(10, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        ...
        time.setText("" + elapsedTime);;
    }
});

...

public void actionPerformed(ActionEvent arg0)
{
    if(((JButton) arg0.getSource()).getText().equals("Start"))
    {
        isTiming = true;
        timer.start();
    }
}    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM