0

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. I tried it i.e.

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.

Baz
  • 36,440
  • 11
  • 68
  • 94
Mukesh Kumar Singh
  • 4,512
  • 2
  • 22
  • 30

3 Answers3

6

Better use org.eclipse.swt.widgets.Display.timerExec(int, Runnable) method to update UI on timely manner.

sambi reddy
  • 3,065
  • 1
  • 13
  • 10
3

You're not updating the UI from another thread - you're updating the UI thread from itself.

sleeping on the UI thread will prevent the UI thread from doing things like painting, so it will appear that your program has hung.

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.

For example:

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

    Thread.sleep(1000);
}
Edward Thomson
  • 74,857
  • 14
  • 158
  • 187
0

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();
Mukesh Kumar Singh
  • 4,512
  • 2
  • 22
  • 30