JavaFX FileChooser and DirectoryChooser Tutorial

1- JavaFX FileChooser, DirectoryChooser

The FileChooser allows users to navigate the file system and choose a file or multiple files. A similar component is DirectoryChooser, which allows users to select a folder.
Below is the image of FileChooser/DirectoryChooser running on different OSs.

Mac OS

Windows

Linux

2- FileChooser example

The following example, when the user clicks the button, a FileChooser will display for the user to select the file and open it.
OpenFileChooserDemo.java
package org.o7planning.javafx.filechooser;

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

public class OpenFileChooserDemo extends Application {

    private Desktop desktop = Desktop.getDesktop();

    @Override
    public void start(Stage primaryStage) throws Exception {

        final FileChooser fileChooser = new FileChooser();

        TextArea textArea = new TextArea();
        textArea.setMinHeight(70);

        Button button1 = new Button("Select One File and Open");

        Button buttonM = new Button("Select Multi Files");

        button1.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                textArea.clear();
                File file = fileChooser.showOpenDialog(primaryStage);
                if (file != null) {
                    openFile(file);
                    List<File> files = Arrays.asList(file);
                    printLog(textArea, files);
                }
            }
        });

        buttonM.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                textArea.clear();
                List<File> files = fileChooser.showOpenMultipleDialog(primaryStage);

                printLog(textArea, files);
            }
        });

        VBox root = new VBox();
        root.setPadding(new Insets(10));
        root.setSpacing(5);

        root.getChildren().addAll(textArea, button1, buttonM);

        Scene scene = new Scene(root, 400, 200);

        primaryStage.setTitle("JavaFX FileChooser (o7planning.org)");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void printLog(TextArea textArea, List<File> files) {
        if (files == null || files.isEmpty()) {
            return;
        }
        for (File file : files) {
            textArea.appendText(file.getAbsolutePath() + "\n");
        }
    }

    private void openFile(File file) {
        try {
            this.desktop.open(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Application.launch(args);
    }

}

3- DirectoryChooser example

Use DirectoryChooser to select a folder:
DirectoryChooserDemo.java
package org.o7planning.javafx.filechooser;

import java.io.File;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;

public class DirectoryChooserDemo extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {

        final DirectoryChooser directoryChooser = new DirectoryChooser();
        configuringDirectoryChooser(directoryChooser);

        TextArea textArea = new TextArea();
        textArea.setMinHeight(70);

        Button button = new Button("Open DirectoryChooser and select a directory");

        button.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                File dir = directoryChooser.showDialog(primaryStage);
                if (dir != null) {
                    textArea.setText(dir.getAbsolutePath());
                } else {
                    textArea.setText(null);
                }
            }
        });

        VBox root = new VBox();
        root.setPadding(new Insets(10));
        root.setSpacing(5);

        root.getChildren().addAll(textArea, button);

        Scene scene = new Scene(root, 400, 200);

        primaryStage.setTitle("JavaFX DirectoryChooser (o7planning.org)");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void configuringDirectoryChooser(DirectoryChooser directoryChooser) {
        // Set title for DirectoryChooser
        directoryChooser.setTitle("Select Some Directories");

        // Set Initial Directory
        directoryChooser.setInitialDirectory(new File(System.getProperty("user.home")));
    }

    public static void main(String[] args) {
        Application.launch(args);
    }

}

4- Configuring FileChooser, DirectoryChooser

Set title & initial directory:
// Set title for FileChooser
fileChooser.setTitle("Select Some Files");

// Set Initial Directory
fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));
ConfiguringFileChooserDemo.java
package org.o7planning.javafx.filechooser;

import java.io.File;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

public class ConfiguringFileChooserDemo extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {

        final FileChooser fileChooser = new FileChooser();
        configuringFileChooser(fileChooser);

        TextArea textArea = new TextArea();
        textArea.setMinHeight(70);

        Button button = new Button("Open File Chooser and select some files");

        button.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                fileChooser.showOpenDialog(primaryStage);
            }
        });

        VBox root = new VBox();
        root.setPadding(new Insets(10));
        root.setSpacing(5);

        root.getChildren().addAll(button);

        Scene scene = new Scene(root, 400, 200);

        primaryStage.setTitle("JavaFX FileChooser (o7planning.org)");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void configuringFileChooser(FileChooser fileChooser) {
        // Set title for FileChooser
        fileChooser.setTitle("Select Some Files");

        // Set Initial Directory
        fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));
    }

    public static void main(String[] args) {
        Application.launch(args);
    }

}

5- FileChooser Filters

Next, you can configure FileChooser by adding filters in order to determine which types of file will be displayed on FileChooser. For example, create 3 filters, ALL filter displays all types of files, PNG filter displays png images, and JPG filter only displays jpg images.
// Add Extension Filters

fileChooser.getExtensionFilters().addAll(//
       new FileChooser.ExtensionFilter("All Files", "*.*"), 
       new FileChooser.ExtensionFilter("JPG", "*.jpg"), 
       new FileChooser.ExtensionFilter("PNG", "*.png"));
The filters:
ALL filter - Displays all types of files and folders.
PNG filter shows only the png images or folders.
View full example:
FilterFileChooserDemo.java
package org.o7planning.javafx.filechooser;

import java.io.File;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

public class FilterFileChooserDemo extends Application {

  @Override
  public void start(Stage primaryStage) throws Exception {

      final FileChooser fileChooser = new FileChooser();
      configuringFileChooser(fileChooser);

      TextArea textArea = new TextArea();
      textArea.setMinHeight(70);

      Button button = new Button("Select some Pictures");

      button.setOnAction(new EventHandler<ActionEvent>() {

          @Override
          public void handle(ActionEvent event) {
              fileChooser.showOpenDialog(primaryStage);
          }
      });

      VBox root = new VBox();
      root.setPadding(new Insets(10));
      root.setSpacing(5);

      root.getChildren().addAll(button);

      Scene scene = new Scene(root, 400, 200);

      primaryStage.setTitle("JavaFX FileChooser (o7planning.org)");
      primaryStage.setScene(scene);
      primaryStage.show();
  }

  private void configuringFileChooser(FileChooser fileChooser) {
      // Set title for FileChooser
      fileChooser.setTitle("Select Pictures");

      // Set Initial Directory
      fileChooser.setInitialDirectory(new File("C:/Users/tran/Pictures"));

      // Add Extension Filters
      fileChooser.getExtensionFilters().addAll(//
              new FileChooser.ExtensionFilter("All Files", "*.*"), //
              new FileChooser.ExtensionFilter("JPG", "*.jpg"), //
              new FileChooser.ExtensionFilter("PNG", "*.png"));
  }

  public static void main(String[] args) {
      Application.launch(args);
  }

}

6- Save file example

  • TODO