Java stopwatch that updates GUI every second?

I'm a Java beginner, and I'm trying to create a simple stopwatch program that displays time on a swing GUI. Making a stopwatch is easy, but I can’t find a way to update the GUI every second and display the current time on the stopwatch. How can i do this?

+5
source share
1 answer

Something in this direction should do this:

import java.awt.EventQueue;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JLabel;

/** @see https://stackoverflow.com/a/11058263/230513 */
public class Clock {

    private Timer timer = new Timer();
    private JLabel timeLabel = new JLabel(" ", JLabel.CENTER);

    public Clock() {
        JFrame f = new JFrame("Seconds");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(timeLabel);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
        timer.schedule(new UpdateUITask(), 0, 1000);
    }

    private class UpdateUITask extends TimerTask {

        int nSeconds = 0;

        @Override
        public void run() {
            EventQueue.invokeLater(new Runnable() {

                @Override
                public void run() {
                    timeLabel.setText(String.valueOf(nSeconds++));
                }
            });
        }
    }

    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                final Clock clock = new Clock();
            }
        });
    }
}

timeLabel the number of seconds during which the timer has been started will always be displayed.

  • You will need to format it correctly to display "hh: mm: ss"; one approach is shown here .

  • , .

  • javax.swing.Timer.

+6

All Articles