How to update SWT GUI from another thread in Java

前端 未结 4 706
野性不改
野性不改 2020-12-05 11:36

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

相关标签:
4条回答
  • 2020-12-05 11:53

    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.

    0 讨论(0)
  • 2020-12-05 11:55

    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.

    0 讨论(0)
  • 2020-12-05 12:02

    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!");
     }
    });
    
    0 讨论(0)
  • 2020-12-05 12:17

    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
    0 讨论(0)
提交回复
热议问题