每秒从另一个线程更新swt ui

时间:2013-04-16 13:31:32

标签: java swt ui-thread

我正在为MAC OS开发一个SWT java项目,我需要在SWT UI上添加一个标签,我必须显示当前时间,每秒更新一次。我试过了,即

final Label lblNewLabel_1 = new Label(composite, SWT.CENTER);
FormData fd_lblNewLabel_1 = new FormData();
fd_lblNewLabel_1.left = new FormAttachment(btnNewButton_call, 10);
fd_lblNewLabel_1.bottom = new FormAttachment(100, -10);
fd_lblNewLabel_1.right = new FormAttachment(btnTransfer, -10);
fd_lblNewLabel_1.height = 20;
lblNewLabel_1.setLayoutData(fd_lblNewLabel_1);
    getDisplay().syncExec(new Runnable() {

            @Override
            public void run() {
                while(true){
                    lblNewLabel_1.setText(Calendar.getInstance().getTime().toString());

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                }   
            }
        });

但它不起作用,请帮助我这样做。 提前谢谢。

3 个答案:

答案 0 :(得分:6)

更好地使用org.eclipse.swt.widgets.Display.timerExec(int, Runnable)方法及时更新UI。

答案 1 :(得分:3)

您没有从另一个线程更新UI - 您正在从自身更新UI线程。

UI线程上的

sleep将阻止UI线程执行绘制之类的操作,因此看起来您的程序已挂起。

不是安排UI线程运行更新窗口小部件并休眠一秒的Runnable,而是希望每秒休眠一次的线程,然后安排更新窗口小部件的Runnable 然后快速退出

例如:

while(true)
{
    getDisplay().asyncExec(new Runnable() {
        lblNewLabel_1.setText(Calendar.getInstance().getTime().toString());
    });

    Thread.sleep(1000);
}

答案 2 :(得分:0)

我完全按照以下代码

完成了
Thread timeThread = new Thread() {
            public void run() {
                while (true) {
                    display.syncExec(new Runnable() {

                        @Override
                        public void run() {
                            lblNewLabel_1.setText(Calendar.getInstance().getTime().toString());
                        }
                    });

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        timeThread.setDaemon(true);
        timeThread.start();
相关问题