简体   繁体   中英

How to create dynamic text in label in SWT java?

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.");
            }
        });

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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