在多线程的SWT程序中,线程为什么不能访问SWT控件呢?
下面的代码运行的话会抛出org.eclipse.swt.SWTException: Invalid thread access
要怎么样做 才可以使 多线程可以访问呢?
而没有多线程的话,界面就会失去响应。
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class Test {
public static void main(String[] args) {
Display display = Display.getDefault();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final Text t = new Text(shell, SWT.BORDER | SWT.CENTER);
new Thread(new Runnable() {
public void run() {
int i = 0;
while (true) {
i++;
t.setText(String.valueOf(i));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
}