【问题标题】:XDEVTextField's value isn't updated to real timeXDEVTextField 的值未实时更新
【发布时间】:2021-01-26 11:12:05
【问题描述】:

我有一个需要每秒实时更新的 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 元素的所有属性,但似乎没有任何原因。任何建议或解决方案将不胜感激。

【问题讨论】:

    标签: java date time timer rapidclipse


    【解决方案1】:

    您只能使用 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();
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2017-12-06
      • 2017-09-22
      • 2013-06-27
      • 1970-01-01
      • 2018-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多