SWT在运行耗时的UI任务时显示Progressbar

时间:2014-07-20 11:13:32

标签: java multithreading swt

我需要在运行耗时的任务时显示progresbar 问题是此任务必须访问UI(读取和更新),因此我无法使用

Display.asyncExec(new Runnable() {...})

因为只有一个UI线程...

还有一个从匿名类(runnable ...)

返回数据的复杂性

请告知可以做些什么。

1 个答案:

答案 0 :(得分:2)

从不在主线程上运行长时间运行的任务。这是其他线程的用途。 您仍然可以从其他线程更新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();
}
相关问题