我需要在运行耗时较长的任务时显示进度条。
问题是这个任务必须访问UI(读取和更新),因此我将无法使用
Display.asyncExec(new Runnable() {...})
由于只有一个UI线程…
从匿名类(可运行的…)返回数据也很复杂
请告知可以做些什么
请不要在主线程上运行长时间运行的任务。这就是其他线程的作用。您仍然可以从另一个线程更新GUI。下面是一个例子:
public static void main(String[] args)
{
final Display display = new Display();
final Shell shell = new Shell();
shell.setLayout(new FillLayout());
final Label label = new Label(shell, SWT.NONE);
new Thread(new Runnable()
{
@Override
public void run()
{
int counter = 0;
while (label != null && !label.isDisposed())
{
final String text = Integer.toString(counter++);
display.asyncExec(new Runnable()
{
@Override
public void run()
{
if (label != null && !label.isDisposed())
label.setText(text);
}
});
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}).start();
shell.pack();
shell.setSize(200, 100);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
}