5

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

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

我想timeLabel在 EDT 以外的另一个线程中刷新文本。
我做对了吗?还有其他更好的方法吗?
另外作为信息,我已经添加timeLabel到包含几个类似实用程序的 a 中,并在另一个中调用。extendedJPanelMainJFrame

4

1 回答 1

14

您可以在没有 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();
于 2012-03-24T20:10:49.800 回答