Search code examples
javaswingswingworkerjavax.swing.timer

Using SwingWorker and Timer to display time on a label?


I want to have a clock showing current time and refreshes every second. The code I am using is:

int timeDelay = 1000;
ActionListener time;
time = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent evt) {
            timeLabel.setText(DateTimeUtil.getTime()); 
            /*timeLabel is a JLabel to display time,
            getTime() is samll static methos to return formatted String of current time */
        }
    };
SwingWorker timeWorker = new SwingWorker() {

        @Override
        protected Object doInBackground() throws Exception {

            new Timer(timeDelay, time).start();
            return null;
        }
    };
timeWorker.execute();

What I want to refresh the timeLabel text in another thread other than EDT.
Am I doing it correct? Any other better way?
Also for information, i've added timeLabel to a extendedJPanel which contains few similar kinds of utilities, and is called in another MainJFrame.


Solution

  • You can do this without a SwingWorker, because this is what the Swing Timer is made for.

    int timeDelay = 1000;
    ActionListener time;
    time = new ActionListener() {
    
        @Override
        public void actionPerformed(ActionEvent evt) {
            timeLabel.setText(DateTimeUtil.getTime()); 
            /* timeLabel is a JLabel to display time,
               getTime() is samll static methos to return 
               formatted String of current time */
        }
    };
    
    new Timer(timeDelay, time).start();