JavaFX

JavaFX FileChooser Example

This article shows examples of JavaFX file choosers. The FileChooser class is defined in the javafx.stage package.

1. Overview

A file chooser provides a simple mechanism for the user to choose a file. File choosers provide a GUI for navigating the file system, and then allows either choosing a file, or entering the name of a file to be saved. There are three types of file chooser dialogs: for selecting single file or multiple files and a file save dialog.

These dialogs have look and feel of the platform UI components which is independent of JavaFX.

1.1. Configuring

The file chooser can be configured with following properties:

  • Title: This defines the dialog’s title bar title. If none is set, a default value is used. For example, for a single file chooser dialog it is set as “Open”.
  • Initial directory: This is the initial directory set for the dialog. If none is set, a default value is used; this varies for different operating systems.
  • Extension filter: An extension filter is used for filtering which files can be chosen in a file chooser based on the file name extensions. The FileChooser.ExtensionFilter is a static final class, defines an extension filter. An example extension filter is created as follows: new ExtensionFilter("PDF Files", "*.pdf"). This specifies only files with “pdf” extension are shown in the file chooser dialog. Multiple file extensions can be specified for a single filter as follows: new ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif"). Also, a file chooser can have multiple extension filters.
  • Initial file name: There is a property to set the initial file name (or default file name) while saving a file. This is specific to save file chooser dialog.

The examples in this article demonstrate the API usage of these properties.

1.2. Showing

The three types of the file chooser dialogs are displayed using following methods. The first two methods are for selecting file(s) and the third method is for saving files.

  • showOpenDialog(): returns File
  • showOpenMultipleDialog(): returns List<File>
  • showSaveDialog(): returns File

The user has a choice to select file(s) or cancel the dialog (using Cancel button or ‘X’ button on title bar). In case of a cancel, the show*() method returns a null.

These methods are blocking methods; that is the code after the show* method does not execute until the dialog is closed.

1.3. Examples

This article has two examples. The first shows the usage of the two select (single and multiple) file chooser dialogs and the second example shows the usage of a save file chooser dialog. The multiple select file chooser, in addition, is configured to use an extension filter.

The following sections describe the examples with code snippets and GUI pictures. The complete source code for the examples is included in the section 4. Download Java Source Code, at the bottom of this post. The example programs are compiled and run on Windows 7 operating system and require JavaFX 8 (Java SE 8).

2. Select File Choosers Example

This example program demonstrates the file select file chooser dialogs – both single file and multiple files (filtered).

The following is the example’s main window:

Figure 1 : Select File Choosers Example
Figure 1 : Select File Choosers Example

2.1. Single File Select File Chooser

From the main window: click the Choose a file… button.

This opens a file chooser dialog. This is configured to get default title and initial directory properties. Navigate through the file system and select any file, for example a file with name “jdbc4.0-spec.pdf” in a directory. Click the Open button. This closes the dialog and the status message on the main window shows “File selected: jdbc4.0-spec.pdf”.

Open the file chooser again and cancel the dialog. The status message shows “File selection cancelled”.

The following is the code for creating, showing and capturing the result of the file chooser:

FileChooser fileChooser = new FileChooser();
File selectedFile = fileChooser.showOpenDialog(null);

if (selectedFile != null) {

    actionStatus.setText("File selected: " + selectedFile.getName());
}
else {
    actionStatus.setText("File selection cancelled.");
}

The file chooser dialog is displayed using the method showOpenDialog(Window owner). The owner Window value is the window that displays the dialog. If an owner window is specified as a null, the dialog is displayed as non-modal. In case an owner window is specified the dialog is modal. The code above has a null for the owner window.

The method returns a File object, and this is the selected file. The value is null if the dialog is cancelled and there is no selection. Also, note that the title and initial directory properties are not set and default values are used.

2.2. Multiple Files Select File Chooser

From the main window: click the Choose multiple PDF files… button.

This opens a file chooser dialog. This is configured with title, initial directory properties and an extension filter. The filter allows only selection of PDF type files (files with “.pdf” extension).

The following code shows creating the file chooser dialog, its configuration, the extension filter, showing the dialog and capturing the result:

FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Select PDF files");
fileChooser.setInitialDirectory(new File("X:\\testdir\\two"));
fileChooser.getExtensionFilters().addAll(
        new ExtensionFilter("PDF Files", "*.pdf"));

List<File> selectedFiles = fileChooser.showOpenMultipleDialog(savedStage);

if (selectedFiles != null) {

    actionStatus.setText("PDF Files selected [" + selectedFiles.size() + "]: " + selectedFiles.get(0).getName() + "..");
}
else {
    actionStatus.setText("PDF file selection cancelled.");
}

The showOpenMultipleDialog(Window owner) method shows a modal dialog and returns a List collection of type File, when file(s) are selected and dialog is closed. In case the dialog is cancelled the method returns a null.

In the above code the lines 4 and 5 show the extension filter configuration.

The following picture shows the multiple file chooser dialog with PDF file extension filter. Note this GUI is specific to Windows 7 operating system.

Figure 2 : Multiple File Chooser Dialog
Figure 2 : Multiple File Chooser Dialog

3. Save File Chooser Example

This example program demonstrates the save file chooser dialog construction and its usage. The following is the example’s main window:

Figure 3 : Save File Chooser Example
Figure 3 : Save File Chooser Example

From the main window enter some text in the text area and click the Save as file… button. This opens a save file chooser dialog.

Navigate to the required directory and enter a file name with “.txt” extension – or use the default file name “MyFile.txt”. Click the Save button. This saves the file with the text entered in the text area and closes the dialog. The status message on the main window shows the path to the saved file, for example “File saved: C:\MyFile.txt”

In case the Cancel button is clicked in the save file chooser dialog, the dialog closes without saving a file. The status message on the main window shows “File save cancelled”.

The following code shows creating the save file chooser dialog, its configuration, showing and capturing the result:

FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Save file");
fileChooser.setInitialFileName(defaultFileName);
File savedFile = fileChooser.showSaveDialog(savedStage);

if (savedFile != null) {

    try {
        saveFileRoutine(savedFile);
    }
    catch(IOException e) {
	
        e.printStackTrace();
        actionStatus.setText("An ERROR occurred while saving the file!");
        return;
    }

    actionStatus.setText("File saved: " + savedFile.toString());
}
else {
    actionStatus.setText("File save cancelled.");
}

In the above code the save file chooser dialog is constructed and its title and initial file name properties are configured. The initial file name is the default file name the dialog shows in the “File name” text field, and the file name can be overridden by the user. The dialog is opened as a modal window using the method showSaveDialog(Window owner). On saving the dialog, the method returns a File object that represents the saved file or a null in case the dialog is cancelled.

The saveFileRoutine(File savedFile) method (see line 9 in the above code) creates a new file using the file path information (savedFile variable), and writes the text from the text area into the file. The created (saved) file can be opened using a plain text editor, like a Notepad program on Windows operating system.

The following picture shows the save file chooser dialog with initial file name “MyFile.txt”. Note this GUI is specific to Windows 7 operating system.

Figure 4 : File Chooser Save Dialog
Figure 4 : File Chooser Save Dialog

4. Download Java Source Code

This was an example of javafx.stage.FileChooser

Download
You can download the full source code of this example here: FxFileChooserExamples.zip

Prasad Saya

Prasad Saya is a software engineer with over ten years’ experience in application development, maintenance, testing and consulting on various platforms. He is a certified Java and Java EE developer. At present his interest is in developing Java applications. He also has experience working with databases and ERP applications.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Lam
Lam
5 years ago

Thank you for your code and for your explanation. I’m a student that works at the same time and I didn’t totally understand how to use File Chooser. Now I think it’ll be clear. :)

Akumu Bavon
Akumu Bavon
4 years ago

How can i get the chosen file’s directory?

Back to top button