File Dialogs  «Prev  Next»


Lesson 5 Choosing Files with JavaFX and Swing Dialog Boxes
Objective Use JavaFX and Java Foundation Classes (Swing) to open modern file dialog boxes and handle user events effectively.

Choosing Files with Modern Java Dialog Boxes

Modern Java development has moved beyond AWT's FileDialog toward richer GUI frameworks provided by the Java Foundation Classes (Swing) and JavaFX, now maintained as the open-source OpenJFX project within OpenJDK. Both Swing and JavaFX offer native-feeling, customizable file chooser dialogs that support single and multiple file selection across platforms.

1. Choosing Files with JavaFX

JavaFX provides a robust and modern approach for file selection using the javafx.stage.FileChooser class. Unlike AWT or Swing, JavaFX dialogs are part of a scene graph architecture, making them ideal for modern desktop and hybrid (JavaFX + FXML) applications.

Single File Selection Example


import javafx.application.Application;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.File;

public class JavaFXFileChooserExample extends Application {
    @Override
    public void start(Stage primaryStage) {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("Open a File");
        fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));

        // Optional filter: limit to text files
        fileChooser.getExtensionFilters().add(
            new FileChooser.ExtensionFilter("Text Files", "*.txt")
        );

        File selectedFile = fileChooser.showOpenDialog(primaryStage);
        if (selectedFile != null) {
            System.out.println("Selected file: " + selectedFile.getAbsolutePath());
        } else {
            System.out.println("No file selected.");
        }
    }

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


When showOpenDialog() is invoked, JavaFX automatically blocks user interaction with other windows until the dialog is closed. This modern API supports filters, customizable titles, and platform-native integration.

Multiple File Selection

JavaFX also allows users to select multiple files at once with showOpenMultipleDialog():


List<File> selectedFiles = fileChooser.showOpenMultipleDialog(primaryStage);
if (selectedFiles != null) {
    selectedFiles.forEach(f -> System.out.println(f.getAbsolutePath()));
}

2. Swing JFileChooser (Java Foundation Classes)

Swing’s JFileChooser remains a standard and reliable file selection tool within the Java Foundation Classes (JFC). It offers a comprehensive API for selecting files and directories while supporting multiple modes (open, save, and custom dialogs).

Example Using JFileChooser


import javax.swing.*;
import java.io.File;

public class SwingFileChooserExample {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFileChooser chooser = new JFileChooser();
            chooser.setDialogTitle("Select Files");
            chooser.setMultiSelectionEnabled(true);
            chooser.setCurrentDirectory(new File(System.getProperty("user.home")));

            int result = chooser.showOpenDialog(null);
            if (result == JFileChooser.APPROVE_OPTION) {
                for (File file : chooser.getSelectedFiles()) {
                    System.out.println("Selected: " + file.getAbsolutePath());
                }
            } else {
                System.out.println("Operation cancelled.");
            }

        });
    }
}

This Swing-based approach is suitable for legacy applications or projects that already depend on the JFC GUI toolkit. However, for newer desktop applications or those using FXML-based views, JavaFX is the recommended framework.

3. Event Handling in JavaFX vs. Legacy AWT

Older versions of Java (1.0 and 1.1) handled GUI events by subclassing AWT components and manually enabling event masks using enableEvents(long eventMask). This approach was both verbose and inefficient, leading to the introduction of the modern event delegation model.

In JavaFX, event handling follows a clean and declarative model:


Button openButton = new Button("Open File");
openButton.setOnAction(event -> {
    File selectedFile = fileChooser.showOpenDialog(primaryStage);
    if (selectedFile != null) {
        System.out.println("File chosen: " + selectedFile.getName());
    }
});

JavaFX’s event model uses EventHandler<ActionEvent> interfaces and lambda expressions to streamline code. This structure integrates seamlessly with FXML controllers, making it ideal for modern GUI architectures.

4. Why OpenJFX Matters

The JavaFX toolkit became an open-source project known as OpenJFX and is now part of the OpenJDK ecosystem. Its modular design (beginning with Java 11) enables lightweight runtime inclusion and flexibility for building modern, cross-platform desktop apps. OpenJFX continues to evolve independently of the JDK, with active updates to UI components, accessibility, and performance.

Summary

While AWT’s FileDialog was a foundational component for early Java GUIs, modern Java development relies on JFileChooser (Swing) and FileChooser (JavaFX) for user-friendly file selection. Event handling has transitioned from subclass-based AWT approaches to clean, declarative listener models in JavaFX and Swing. Developers today benefit from OpenJFX’s active maintenance and integration with modern Java tooling, ensuring a more stable, responsive, and secure GUI development experience.


In the next module, we’ll explore customizing JavaFX FileChooser filters and integrating asynchronous I/O operations for large file handling using the java.nio.file package.


SEMrush Software