简体   繁体   English

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

[英]Updating swt ui from another thread every second

I am working on a SWT java project for MAC OS, i need to add a label on SWT UI where i have to show the current time, updating on every second. 我正在针对MAC OS的SWT java项目中工作,我需要在SWT UI上添加一个标签,其中我必须显示当前时间,并每秒更新一次。 I tried it ie 我尝试过

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();
                }
                }   
            }
        });

but its not working, please help me do that. 但它不起作用,请帮助我。 thanks in advance. 提前致谢。

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

You're not updating the UI from another thread - you're updating the UI thread from itself. 您不是从另一个线程更新UI,而是从自身更新UI线程。

sleep ing on the UI thread will prevent the UI thread from doing things like painting, so it will appear that your program has hung. 在UI线程上sleep会阻止UI线程执行绘画操作,因此您的程序似乎已挂起。

Instead of schedule the UI thread to run a Runnable that updates a widget and sleeps for a second, you want a thread that sleeps every second and then schedules a Runnable that updates the widget and then exits quickly . 您不是希望UI线程运行运行可更新小部件并休眠一秒钟的Runnable ,而是希望一个线程每秒钟休眠一次,然后调度可更新小部件然后快速退出Runnable

For example: 例如:

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

    Thread.sleep(1000);
}

I did it exactly..using following code 我完全做到了..使用以下代码

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM