Reputation: 75
I am trying to write a code including a button and a label.
I want, when user click the button, the label shows TEXTA, then after three seconds it shows TEXTB. What I see is when I click the button, the label wait for 3 seconds and shows TEXTB. Here is my code:
Label lblFindModem = new Label(shell, SWT.NONE);
lblFindModem.setFont(SWTResourceManager.getFont("Ubuntu", 13, SWT.NORMAL));
lblFindModem.setBounds(329, 164, 256, 28);
lblFindModem.setText("Modem is not Initialized");
Button btnFindModem = new Button(shell, SWT.NONE);
btnFindModem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
System.out.println("Someone Clicked the button");
lblFindModem.setText("Unplug the modem for 3 seconds...");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lblFindModem.setText("Plug the modem again.");
}
});
Upvotes: 1
Views: 335
Reputation: 111217
You must never block the main SWT UI thread by calling things like Thread.sleep
. This will make the app completely unresponsive and nothing will happen until the end of the sleep. It is vital than the UI code returns to the main Display.readAndDispatch
loop quickly.
Instead you can use Display.timerExec
to execute some code after a delay:
So replace your code
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lblFindModem.setText("Plug the modem again.");
with:
Display.getCurrent().timerExec(3000, () -> lblFindModem.setText("Plug the modem again."));
(code assumes you are using Java 8 or later)
Upvotes: 3