Mohamed Benmahdjoub
Mohamed Benmahdjoub

Reputation: 1280

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

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

Upvotes: 3

Views: 1797

Answers (1)

James_D
James_D

Reputation: 209340

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?

Upvotes: 6

Related Questions