我有一个SWT按钮的监听器,它的开头如下:
button1.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Runnable runnable = new Runnable() {
public void run() {
String nextValue = text1.getText();
...
我需要UI中名为text1的Text字段的当前值,但最后一行getText()失败并带有
org.eclipse.swt.SWTException: Invalid thread access
我知道syncExec / asyncExec(我的代码有几个),但StackOverflow的其他线程建议您只需要在UI中更新字段时使用它。在侦听器中读取UI字段的正确方法是什么?
答案 0 :(得分:2)
以下是一些演示如何同步运行代码的代码片段。异步(从Lars Vogel's非常有用的网站复制)。
// 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
}
});