多线程JAVA如何在线程中循环时修改SWT UI
我正在尝试实现一个桌面应用程序,它通过一个函数循环,并每1秒在UI上设置一个文本字段
但我要么
org.eclipse.swt.SWTException: Invalid thread access
当我不使用显示器时
或者当我这样做的时候,UI真的很慢
display.asyncExec(new Runnable() {
我的代码如下所示:
public void open() {
Display display = Display.getDefault();
shell = new Shell();
shell.setSize(486, 322);
shell.setText("SWT Application");
Button btnStartLoop = new Button(shell, SWT.NONE);
btnStartLoop.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
SwingUtilities.invokeLater(new Runnable() {
public void run() // updates displayArea
{
while (true) {
try {
text.setText("Text has been set");
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
}
});
btnStartLoop.setBounds(35, 30, 75, 25);
btnStartLoop.setText("Start Loop");
text = new Text(shell, SWT.BORDER);
text.setText("0");
text.setBounds(116, 32, 177, 21);
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
有什么办法可以克服这个问题吗
# 1 楼答案
你绝对不能在UI线程中睡觉。必须为后台活动使用新的
Thread
。从线程内调用Display.asyncExec
以在UI线程中运行UI更新代码注意:
SwingUtilities
用于Swing应用程序,不要在SWT应用程序中使用您还可以使用
Display
的timerExec
方法在特定延迟后运行代码,这样就不需要后台线程