如何从 Java 中的另一个线程更新 SWT GUI

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1333377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 08:21:59  来源:igfitidea点击:

How to update SWT GUI from another thread in Java

javamultithreadinguser-interfaceswt

提问by Micha? Ziober

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

我正在使用 SWT 编写桌面应用程序。从另一个线程更新 GUI 控件的最简单方法是什么?

采纳答案by McDowell

Use Display.asyncExecor Display.syncExec, depending on your needs.

根据您的需要使用Display.asyncExecDisplay.syncExec

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

回答by Adamski

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:"

“当涉及到线程问题时,SWT 确实提出了快速失败的观点;所以至少典型的问题在生产之前不会被忽视。但是,问题是,如果你需要更新标签/按钮,你会怎么做来自后台线程的 SWT 中的 /super-duper-control?嗯,它与 Swing 惊人地相似:”

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

回答by nanda

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 线程发送一条消息,说明某些修改已更改。如果您从 MVC 的角度来看,这会更清晰。

回答by McDowell

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.

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