Java 使用SwingWorker和计时器在标签上显示时间?
我想要一个显示当前时间并每秒刷新的时钟。我使用的代码是:Java 使用SwingWorker和计时器在标签上显示时间?,java,swing,swingworker,javax.swing.timer,Java,Swing,Swingworker,Javax.swing.timer,我想要一个显示当前时间并每秒刷新的时钟。我使用的代码是: int timeDelay = 1000; ActionListener time; time = new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { timeLabel.setText(DateTimeUtil.getTime()); /*time
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
添加到一个扩展的JPanel
,它包含很少类似类型的实用程序,并在另一个Main
中调用。您可以在不使用SwingWorker的情况下执行此操作,因为Swing计时器就是为此而设计的
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();
除了@Jonas(1+)提供的极好建议之外,还有一件事是你做得不对,那就是在后台线程中进行Swing调用。SwingWorker的doInBackground()
方法不应包含不能在后台线程上调用的Swing调用,这意味着您不应在该方法内创建Swing计时器,也不应在此处对Swing计时器对象调用start()
。+1获取此建议。非常感谢。还有一件事是,doInBackground()
不能包含Swing调用-这意味着我不应该通过SwingWorker
初始化框架内的Swing组件,如面板、按钮等?绝对正确。SwingWorker用于非Swing初始化以及通过发布、处理和完成方法与Swing通信。Swing Timer中的操作是否在另一个线程中启动???@Asif:该操作在EDT上执行,因为所有GUI修改大部分都是从EDT进行的。@Asif:相反,计时器的延迟
发生在不同的线程上。