Using SwingWorker and Timer to display time on a shortcut?

I want the clock to show the current time and be updated every second. The code I'm 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();

That I want to update the text timeLabelin a different thread than EDT.
Am I doing it right? Any other better way?
In addition, for information I added timeLabelto extended JPanel, which contains several similar types of utilities and is called in another Main JFrame.

+5
source share
1 answer

You can do this without SwingWorker, because that's what the Swing timer is 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();
+11
source

All Articles