FileChooser 打开时无法阻止对话框

Dialog can't be blocked when FileChooser is open

我对打开 FileChooser 时阻止对话框 window 有疑问。当我从主应用 window 打开 FileChooser 时,阻止主应用 window 没有任何问题(使用 fileChooser.showOpenDialog(Main.getPrimaryStage);)。但是当我从 Dialog 打开 Filechooser 时遇到问题。我无法专注于主应用程序 window,因为 Dialog 有 属性 dialog.initOwner(Main.getPrimaryStage());,但我仍然可以专注于 Dialog 并一遍又一遍地打开下一个 FileChooser。 App image view。我能用它做什么?

您可以通过以下方式获取对 window 的引用,该 window 用于显示其 dialogPane 中的对话框:

Window dialogWindow = dialog.getDialogPane().getScene().getWindow();

使用它,您可以将文件选择器的 "owner" 设置为对话框的 window:

Window dialogWindow = dialog.getDialogPane().getScene().getWindow();
File file = fileChooser.showOpenDialog(dialogWindow);

这是一个 SSCCE:

import java.io.File;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.control.DialogPane;
import javafx.scene.layout.StackPane;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.stage.Window;

public class DialogFileChooser extends Application {

    @Override
    public void start(Stage primaryStage) {


        Button button = new Button("Open Dialog...");
        button.setOnAction(e -> createDialog(primaryStage).show());

        StackPane root = new StackPane(button);
        Scene scene = new Scene(root, 400, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private Dialog<ButtonType> createDialog(Window owner) {

        DialogPane dialogPane = new DialogPane();
        dialogPane.getButtonTypes().add(ButtonType.CLOSE);

        Dialog<ButtonType> dialog = new Dialog<>();

        dialog.setDialogPane(dialogPane);

        Button openFile = new Button("Open File...");
        FileChooser fileChooser = new FileChooser();
        openFile.setOnAction(e -> {
            Window dialogWindow = dialog.getDialogPane().getScene().getWindow();
            File file = fileChooser.showOpenDialog(dialogWindow);
            System.out.println(file);
        });
        dialogPane.setContent(new StackPane(openFile));

        dialog.initOwner(owner);
        return dialog ;

    }

    public static void main(String[] args) {
        launch(args);
    }
}