TextInputDialog 仅在第一次显示

TextInputDialog only shown for the first time

参考下面的代码片段:

public class Application extends javafx.application.Application implements ActionListener {

  private java.awt.SystemTray tray;
  private java.awt.TrayIcon trayIcon;
  private java.awt.PopupMenu popupMenu = new PopupMenu();
  private java.awt.MenuItem menuItem = new MenuItem("My Item");

  @Override
  public void start(Stage primaryStage) throws Exception {
    if (!SystemTray.isSupported())
      return;

    menuItem.addActionListener(this);
    popupMenu.add(menuItem);

    trayIcon = new TrayIcon(image, "Title", popupMenu);
    tray = SystemTray.getSystemTray();
    tray.add(trayIcon);
  } 

  @Override
  public void actionPerformed(ActionEvent e){
    Platform.runLater(() -> {
      Optional<String> result = new TextInputDialog().showAndWait();
      if(result.isPresent() && !result.get().isEmpty()){
        ...
      }
    })
  }
}

对话框只会显示一次。第二次或多次触发actionPerformed(),不会弹出,也不会抛出任何异常。

我试过在 Task 上使用 TasksetOnSucceeded(),并在 Task 的基础上开始 Thread。更糟糕的是,对话框根本不会出现,而且也没有产生任何错误。

您需要设置以下内容:

Platform.setImplicitExit(false);

否则,JavaFX 运行时将在您关闭最后一个 window 时关闭,因此 Platform.runLater() 只对您有效一次

来自 Platform 的片段:

Sets the implicitExit attribute to the specified value. If this attribute is true, the JavaFX runtime will implicitly shutdown when the last window is closed; the JavaFX launcher will call the Application.stop() method and terminate the JavaFX application thread. If this attribute is false, the application will continue to run normally even after the last window is closed, until the application calls exit(). The default value is true.