问题描述
我有一个XDEVTextField,它需要每秒进行实时更新。我尝试了this问题中提出的答案,包括使用Executor和Swing Timer。我也尝试过this way。
下面是我的代码:
public class FirstView extends XdevView implements Runnable {
Thread t = null;
String timeString = "";
public FirstView() {
super();
this.initUI();
this.t = new Thread(this);
this.t.start();
}
@Override
public void run() {
// Todo Auto-generated method stub
try {
while (true) {
final Calendar cal = Calendar.getInstance();
final SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
final Date date = cal.getTime();
this.timeString = formatter.format(date);
System.out.println(this.timeString);
this.txtTime.setValue(this.timeString);
Thread.sleep(500); <-- this should be changed to 1000 but I forgot to
}
}
catch (final Exception e) {
e.printstacktrace();
}
}
问题是txtTime
的值根本没有连续更新,该值在线程启动时仅设置了一次
,而System.out.println(dateandtime.format(date));
仍可以实时输出到控制台,如下所示:
我正在使用Rapidclipse 3.1.1。我在Netbeans上使用Java Swing的JLabel制作了类似的数字时钟。我不知道这里可能是什么问题。我怀疑并检查了txtTime
元素的所有属性,但似乎没有什么原因。任何建议或解决方案将不胜感激。
解决方法
您只能使用access()方法访问UI,该方法将锁定会话以防止冲突。
@Override
public void run() {
try {
while (true) {
this.time = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date());
System.out.println(this.time);
UI.getCurrent().access(()->this.button.setCaption(this.time));
this.t.sleep(1000);
}
} catch (final InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}