繁体   English   中英

如何在 SWT java 中的标签中创建动态文本?

[英]How to create dynamic text in label in SWT java?

我正在尝试编写包含按钮和标签的代码。

我想要,当用户单击按钮时,标签显示 TEXTA,然后在三秒钟后显示 TEXTB。 我看到的是当我单击按钮时,标签等待 3 秒并显示 TEXTB。 这是我的代码:

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

绝不能通过调用诸如Thread.sleep东西来阻塞主 SWT UI 线程。 这将使应用程序完全无响应,并且在睡眠结束之前不会发生任何事情。 重要的是 UI 代码快速返回到主Display.readAndDispatch循环。

相反,您可以使用Display.timerExec在延迟后执行一些代码:

所以替换你的代码

try {
   Thread.sleep(3000);
} catch (InterruptedException e) {
   // TODO Auto-generated catch block
  e.printStackTrace();
}
lblFindModem.setText("Plug the modem again.");

和:

Display.getCurrent().timerExec(3000, () -> lblFindModem.setText("Plug the modem again."));

(代码假定您使用的是 Java 8 或更高版本)

暂无
暂无

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

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