JavaFX - Why is my FileChooser giving me access to the origin Stage?

為{幸葍}努か 提交于 2019-12-10 18:23:07

问题


When i click on the button, a FileChooser is opened. However, i can for example close the Original Stage while the FileChooser is still opened, or i still can click and switch the actual window. Check the code below

My questions are :
1- How can i make the FileChooser Closes when i close the main window ?
2- How can i make the main window not clickable when the FileChooser is opened ?

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

回答1:


According to the JavaDocs

If the owner window for the file dialog is set, input to all windows in the dialog's owner chain is blocked while the file dialog is being shown.

However, you are setting the owner window to a window that is not on the screen, so I think there is no "owner chain" in that case, and the file chooser is effectively not modal.

Why not just do

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

so that you make the owner window of the file chooser the actual window?



来源:https://stackoverflow.com/questions/29519518/javafx-why-is-my-filechooser-giving-me-access-to-the-origin-stage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!