使用SwingWorker和Timer在标签上显示时间?

时间:2012-03-24 19:56:27

标签: java swing swingworker javax.swing.timer

我希望有一个时钟显示当前时间并每秒刷新一次。我正在使用的代码是:

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();

我想刷新除EDT之外的另一个帖子中的timeLabel文本 我做得对吗?还有其他更好的方法吗?
另外,有关信息,我已将timeLabel添加到 extended JPanel,其中包含几种类似的实用程序,并在另一个 {{ 1}} Main

1 个答案:

答案 0 :(得分:12)

您可以在没有SwingWorker的情况下执行此操作,因为这就是Swing Timer的用途。

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();