首页 > 解决方案 > FileChooser 打开时无法阻止对话框

问题描述

当我打开 FileChooser 时,我有关于阻止对话框窗口的问题。fileChooser.showOpenDialog(Main.getPrimaryStage);当我从主应用程序窗口打开 FileChooser 时,阻止应用程序的主窗口(使用)没有任何问题。但是当我从 Dialog 打开 Filechooser 时遇到问题。我不能专注于主应用程序窗口,因为 Dialog 具有 property dialog.initOwner(Main.getPrimaryStage());,但我仍然可以专注于 Dialog 并一遍又一遍地打开下一个 FileChooser。应用图像视图。我能用这个做什么?

标签: javafxjavafx-8

解决方案


您可以通过以下方式获得对用于显示对话框的窗口的引用dialogPane

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

使用它,您可以使文件选择器的“所有者”成为对话框的窗口:

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

推荐阅读