Friday, March 9, 2012

JavaFX 2.0 - Disable owner window for FileChooser

In last article "JavaFX 2.0: FileChooser, set initial directory from last directory", showOpenDialog(Window ownerWindow) was called with ownerWindow of "null". Such that the user can touch the parent window and re-open another FileChooser, can cause error!

We can pass the owner window, primaryStage, to showOpenDialog(primaryStage). Such that it will be blocked while the file dialog is being shown.

 * To change this template, choose Tools | Templates
 * and open the template in the editor.
package javafx_filechooser;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

 * @author Seven
public class JavaFX_FileChooser extends Application {
    File file;

     * @param args the command line arguments
    public static void main(String[] args) {
    public void start(final Stage primaryStage) {
        primaryStage.setTitle("Hello World!");
        final Label labelFile = new Label();
        Button btn = new Button();
        btn.setText("Open FileChooser'");
        btn.setOnAction(new EventHandler<ActionEvent>() {

            public void handle(ActionEvent event) {
                FileChooser fileChooser = new FileChooser();
                //Open directory from existing directory
                if(file != null){
                    File existDirectory = file.getParentFile();

                //Set extension filter
                FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("AVI files (*.avi)", "*.avi");
                //Show open file dialog, with primaryStage blocked.
                file = fileChooser.showOpenDialog(primaryStage);
        VBox vBox = new VBox();
        vBox.getChildren().addAll(labelFile, btn);
        StackPane root = new StackPane();
        primaryStage.setScene(new Scene(root, 300, 250));;

Related article:
- Use FileChooser.showOpenMultipleDialog() to open multi files.


  1. nice entry. good to know there is someone out there dealing with javafx.
    do you know why the file dialogs stays open even if you close the primary stage ?

  2. I appreciate this example!! Thanks

  3. Thanks, this helps me alot...!