[英]Using SwingWorker and Timer to display time on a label?
I want to have a clock showing current time and refreshes every second. 我希望有一个时钟显示当前时间并每秒刷新一次。 The code I am using is:
我使用的代码是:
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();
What I want to refresh the timeLabel
text in another thread other than EDT. 我想在EDT以外的其他线程中刷新
timeLabel
文本。
Am I doing it correct? 我做得对吗? Any other better way?
还有其他更好的办法?
Also for information, i've added timeLabel
to a extended
JPanel
which contains few similar kinds of utilities, and is called in another Main
JFrame
. 另外,为了获取信息,我已将
timeLabel
添加到包含很少类似实用程序的extended
JPanel
中,并在另一个Main
JFrame
调用。
You can do this without a SwingWorker, because this is what the Swing Timer is made for. 你可以在没有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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.