Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何避免org.eclipse.swt.swt异常:线程访问无效_Java_Swt_Listener - Fatal编程技术网

Java 如何避免org.eclipse.swt.swt异常:线程访问无效

Java 如何避免org.eclipse.swt.swt异常:线程访问无效,java,swt,listener,Java,Swt,Listener,我有一个SWT按钮的侦听器,它的开头如下: button1.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Runnable runnable = new Runnable() { public void run() { String nextValue = text1.getText();

我有一个SWT按钮的侦听器,它的开头如下:

button1.addSelectionListener(new SelectionAdapter() {
  @Override
  public void widgetSelected(SelectionEvent e) {
    Runnable runnable = new Runnable() {
      public void run() {
        String nextValue = text1.getText();
        ...
我需要UI中名为text1的文本字段的当前值,但最后一行getText()失败

org.eclipse.swt.swt异常:线程访问无效


我知道syncExec/asyncExec(我的代码有几个),但是StackOverflow的其他线程建议您只在需要更新UI中的字段时使用它。在侦听器中读取UI字段的正确方法是什么?

以下是一些代码片段,演示如何同步和异步运行代码(从非常有用的站点复制)


与SWT UI对象的所有交互都必须在UI线程上运行,而不仅仅是更新。为什么在这里使用
Runnable
。。。。恕我直言,我告诉过你我知道asyncExec,我的代码中有一些,所以我知道如何编写它们。它不能从我自己的用户界面读取字段。@casgage SWT是单线程的<代码>(a)syncExec是从非UI线程访问小部件的唯一方法-无论代码是“读取”还是“写入”小部件属性。如果其他SO线程声称只需要更新小部件,那么它们就错了。这里有更多关于这个问题的内容。@david只是想说(即使这个问题有点老了),这个答案是完全正确的,因为它帮助我解决了同样的问题。
// Update the user interface asynchronously
Display.getDefault().asyncExec(new Runnable() {
   public void run() {
    // ... do any work that updates the screen ...
   }
});

// Update the user interface synchronously

Display.getDefault().syncExec(new Runnable() {
   public void run() {
    // do any work that updates the screen ...
    // remember to check if the widget
    // still exists
    // might happen if the part was closed
   }
});