2012-03-24 13 views
5

我想要一个显示当前时间的时钟并每秒刷新一次。我使用的代码是:使用SwingWorker和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文本是什么。
我正确吗?任何其他更好的方法?
同样的信息,我已经添加timeLabelextendedJPanel其中包含几个类似的多种公用事业,被称为在另一个MainJFrame

+4

除了来自@Jonas(1+)的出色建议外,您做错的一件事是在后台线程中进行Swing调用。 SwingWorker的'doInBackground()'方法应该不包含无法在后台线程调用的Swing调用,这意味着您绝对不应该在此方法内部创建Swing Timer,也不要在此处调用Swing Timer对象的'start() 。 – 2012-03-24 20:14:14

+0

对此建议+1。谢谢。还有一件事是,'doInBackground()'不能包含Swing调用 - 是不是意味着我不应该通过'SwingWorker'初始化框架内的摆动组件,如按钮等? – Asif 2012-03-24 20:42:33

+2

绝对正确。 SwingWorker用于非Swing初始化和通过发布,过程和完成方法与Swing进行通信。 – 2012-03-24 20:52:56

回答

11

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

摆动计时器中的动作本身是否在不同的线程中启动? – Asif 2012-03-24 20:39:17

+1

@Asif:该动作在EDT上执行,因为alla GUI修改大部分都是从EDT制作的。 – Jonas 2012-03-24 20:47:29

+0

ok ..接受..感谢 – Asif 2012-03-24 20:56:29

相关问题