【问题标题】:How to create dynamic text in label in SWT java?如何在 SWT java 中的标签中创建动态文本?
【发布时间】:2019-12-26 19:47:12
【问题描述】:

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

我想,当用户单击按钮时,标签显示 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.");
            }
        });

【问题讨论】:

  • 如果 UI 线程在 swing 或 Eclipse RCP 中,您不能简单地使用睡眠。

标签: java swt delay windowbuilder


【解决方案1】:

您必须绝不通过调用 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 或更高版本)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-20
    • 2011-12-06
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 2015-12-27
    • 1970-01-01
    相关资源
    最近更新 更多