【问题标题】:Using SwingWorker and Timer to display time on a label?使用 SwingWorker 和 Timer 在标签上显示时间?
【发布时间】:2012-03-24 19:56:27
【问题描述】:

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

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 添加到 extendedJPanel 中,其中包含很少类似的实用程序,并在另一个 Main@ 中调用987654327@.

【问题讨论】:

  • 除了@Jonas (1+) 的出色建议之外,您做错的一件事是从后台线程中进行 Swing 调用。 SwingWorker 的 doInBackground() 方法不应包含无法在后台线程上调用的 Swing 调用,这意味着您绝对不应在此方法内创建 Swing Timer,也不应在此处对 Swing Timer 对象调用 start()
  • +1 获得此建议。谢谢你。还有一件事是,doInBackground() 不能包含 Swing 调用 - 这是否意味着我不应该通过 SwingWorker 初始化框架内的 Swing 组件,如面板、按钮等?
  • 绝对正确。 SwingWorker 用于非 Swing 初始化以及通过 publish、process 和 done 方法与 Swing 通信。

标签: java swing swingworker javax.swing.timer


【解决方案1】:

您可以在没有 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();

【讨论】:

  • Swing Timer 中的 Actions 本身是否在不同的线程中启动??
  • @Asif:该操作在 EDT 上执行,因为所有 GUI 修改大部分都是从 EDT 进行的。
  • @Asif:相反,计时器的delay 发生在不同的线程上。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-21
  • 2023-03-31
  • 1970-01-01
  • 2020-07-23
  • 1970-01-01
  • 2012-12-20
相关资源
最近更新 更多