简体   繁体   中英

How to update SWT GUI from another thread in Java

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

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();
        }
      }
    });
  }

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!");
 }
});

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.

从主线程创建单独的线程时,将Gui对象传递给新线程,您可以访问该GUI对象的所有属性。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM