Search code examples
javajavafxjava-8javafx-8filechooser

Prevent window from being focused when FileChooser is active


I have a simple JavaFX application, and I am opening a FileChooser just by calling showOpenDialog().

I want to disable my main window from being selected while the file chooser is open, and keep it on top of the main window if possible.

Thanks for any help given.


Solution

  • From the doc of showOpenDialog (emphasis mine):

    Shows a new file open dialog. The method doesn't return until the displayed open dialog is dismissed. The return value specifies the file chosen by the user or null if no selection has been made. 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.

    So because of the owner chain, in this case both the primaryStage and the secondStage are blocked:

    primaryStage.setScene(new Scene(new VBox(), 300, 300));
    primaryStage.show();
    
    Stage secondStage = new Stage();
    secondStage.setScene(new Scene(new VBox(), 50, 50));
    secondStage.initOwner(primaryStage);
    
    secondStage.show();
    
    FileChooser fc = new FileChooser();
    fc.showOpenDialog(secondStage);
    

    If you modify the last line as

    fc.showOpenDialog(primaryStage);
    

    the primaryStage is blocked, but the secondStage is available.


    Finally, if you do not execute this line:

    secondStage.initOwner(primaryStage);
    

    and you call the last line as

    fc.showOpenDialog(secondStage);
    

    the primaryStage is not blocked, but the secondStage is blocked.