JavaFX-为什么我的FileChooser可以访问原始舞台?

Cal*_*ips 3 events javafx button filechooser javafx-8

当我单击该按钮时,将打开一个FileChooser。但是,例如,当FileChooser仍然打开时,我可以关闭原始舞台,或者我仍然可以单击并切换实际窗口。检查下面的代码

我的问题是:
1-关闭主窗口时如何关闭FileChooser?
2-打开FileChooser后如何使主窗口不可单击?

package application;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.Window;

public class Main extends Application {

    @Override public void start(Stage stage) {

        stage.setTitle("Main Stage");
        stage.setWidth(500);
        stage.setHeight(500);
        stage.show();
        Button button = new Button();
        AnchorPane ap = new AnchorPane();
        Scene scene = new Scene(ap);
        ap.getChildren().addAll(button);
        stage.setScene(scene);

        button.setOnAction(new EventHandler<ActionEvent>() {
            @Override public void handle(ActionEvent e) {
                FileChooser fileChooser = new FileChooser();
                Stage stage2=new Stage();
                stage2.initOwner(stage);
                stage2.initModality(Modality.WINDOW_MODAL);
                fileChooser.showOpenDialog(stage2);  
           }
       });  
    }

    public static void main(String[] args) {
        launch(args);
    }
}
Run Code Online (Sandbox Code Playgroud)

Jam*_*s_D 5

根据JavaDocs

如果设置了文件对话框的所有者窗口,则在显示文件对话框时,将阻止对话框所有者链中所有窗口的输入。

但是,您将所有者窗口设置为不在屏幕上的窗口,因此我认为在这种情况下没有“所有者链”,并且文件选择器实际上不是模态的。

为什么不做

    button.setOnAction(new EventHandler<ActionEvent>() {
        @Override public void handle(ActionEvent e) {
            FileChooser fileChooser = new FileChooser();
            fileChooser.showOpenDialog(stage); 
       }
   });
Run Code Online (Sandbox Code Playgroud)

这样就可以使文件选择器的所有者窗口成为实际窗口?