My problem is to change a background color in a runnable. I am trying to change the background color of a label like traffic lights do (red -> yellow -> green) and I have not much experience with SWT. So I do not see why my attempt doesn't work:
Display.getDefault().asyncExec(new Runnable() {
public void run()
{
label.setBackground(red);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
label.setBackground(yellow);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
label.setBackground(green);
}
});
What happens is that nothing is changing during the waiting time (2*1 second) and the last color (in this case green) is shown - no red and no yellow. Could you please give me a hint what my mistake is? Or an idea how to solve this problem?
Display.asyncExec
runs the entire Runnable
in the User Interface thread. So your two Thread.sleep
calls run in the UI thread and stop the thread from updating the UI.
To do something with a delay use the timerExec
method of Display
to schedule a Runnable
to run after a delay.
// Set first color. Note: use `asyncExec` if you are not in the UI thread
label.setBackground(red);
// Schedule changes
Display.getDefault().timerExec(1000, new Runnable() {
@Override
public void run()
{
if (!label.isDisposed()) {
label.setBackground(yellow);
}
}
});
Display.getDefault().timerExec(2000, new Runnable() {
@Override
public void run()
{
if (!label.isDisposed()) {
label.setBackground(green);
}
}
});