任何更改 UI 对象的 SWT 操作都必须在 SWT 用户界面线程上运行。
在你的情况下text.setText(i.toString());
line 是一个 SWT UI 操作,并且在不同的线程中运行。
您可以使用asyncExec
or syncExec
的方法Display
在 UI 线程中运行一些代码。所以替换:
text.setText(i.toString());
with
final String newText = i.toString();
Display.getDefault().asyncExec(() -> text.setText(newText));
(假设您使用的是 Java 8)。
Using asyncExec
将异步更新 UI。使用syncExec
相反,如果您想暂停线程直到更新完成。
如果您使用的是 Java 7 或更早版本,请使用:
final String newText = i.toString();
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
text.setText(newText);
}
});
请注意,您还应该检查Shell
被处置并停止你的后台线程。如果您不这样做,您将在关闭应用程序时收到错误消息。你的代码递增i
也是错误的。该线程的工作原理:
new Thread(() -> {
for (int i = 1; true; i++) {
try {
Thread.sleep(1000);
} catch (final InterruptedException e) {
return;
}
if (shell.isDisposed()) // Stop thread when shell is closed
break;
final String newText = Integer.toString(i);
Display.getDefault().asyncExec(() -> text.setText(newText));
}
}).start();