Java SWT 更改所选小部件上的标签文本在 Mac 上不起作用



在我的java swt应用程序中,我有以下代码。在按钮选择我需要更改标签的文本两次,一次是在运行线程之前,另一个是在线程完成后。它适用于窗口,但在 Mac 上它不显示第一个文本。为什么这在 Mac 上不起作用?

button.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent arg0) {
            statusLabel.setText("Running...");
            Thread background = new Thread() {
               @Override
               public void run() {
               // Long running task
               }
            };
            background.start();
            try {
                background.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            statusLabel.setText("Finished");
        }
    });

Thread.join 的调用会阻塞 UI 线程,这将导致它停止响应。在发生这种情况之前,确切的更新量取决于每个平台上SWT实现的详细信息。

代码完成后,应从后台线程更新 UI。

像这样:

button.addSelectionListener(new SelectionAdapter() {
   public void widgetSelected(SelectionEvent arg0) {
      statusLabel.setText("Running...");
      Thread background = new Thread() {
         @Override
         public void run() {
            // Long running task
            // Update UI from background thread
            Display.getDefault().asyncExec(() -> statusLabel.setText("Finished"));
         }
      };
      background.start();
  }
});

最新更新