How to update SWT GUI from another thread in Java

混江龙づ霸主 提交于 2019-11-26 22:55:28

问题


I am writing a desktop application using SWT. What is the simplest way to update GUI controls from another thread?


回答1:


Use Display.asyncExec or Display.syncExec, depending on your needs.

For example, another thread might call this method to safely update a label:

  private static void doUpdate(final Display display, final Label target,
      final String value) {
    display.asyncExec(new Runnable() {
      @Override
      public void run() {
        if (!target.isDisposed()) {
          target.setText(value);
          target.getParent().layout();
        }
      }
    });
  }
  • More here



回答2:


There's a tutorial here.

"SWT does make a point to fail-fast when it comes to threading problems; so at least the typical problems don't go unnoticed until production. The question is, however, what do you do if you need to update a label/button/super-duper-control in SWT from a background thread? Well, it's surprisingly similar to Swing:"

// Code in background thread.
doSomeExpensiveProcessing();
Display.getDefault().asyncExec(new Runnable() {
 public void run() {
  someSwtLabel.setText("Complete!");
 }
});



回答3:


You can actually just sent a message to the GUI thread that some modification has been changed. This is cleaner if you see it from MVC perspective.




回答4:


When creating the separate thread from the main thread pass the Gui object to the new thread and u can access all the properties of that GUI object.



来源:https://stackoverflow.com/questions/1333377/how-to-update-swt-gui-from-another-thread-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!