JavaFX FileChooser

A JavaFX FileChooser class (javafx.stage.FileChooser) is a dialog that enables the user to select one or more files via a file explorer from the user's local computer. The JavaFX FileChooser is implemented in the class javafx.stage.FileChooser. In this JavaFX FileChooser tutorial I will show you how to use the JavaFX FileChooser dialog.

Here is an example screenshot of how a JavaFX FileChooser looks:

Creating a FileChooser

In order to use the JavaFX FileChooser dialog you must first create a FileChooser instance. Here is an example of creating a JavaFX FileChooser dialog:

FileChooser fileChooser = new FileChooser();

As you can see, it is pretty easy to create a FileChooser instance.

Showing the FileChooser Dialog

Showing the JavaFX FileChooser dialog is done by calling its showOpenDialog() method. Here is an example of showing a FileChooser dialog:

File selectedFile = fileChooser.showOpenDialog(stage);

The File returned by the showOpenDialog() method is the file the user selected in the FileChooser.

The stage parameter is the JavaFX Stage that should "own" the FileChooser dialog. By "owning" is meant what Stage from which the FileChooser dialog is shown. This will typically be the Stage in which the button sits that initiates the showing of the FileChooser.

Showing a FileChooser is typically done as a result of a click on a button or menu item. Here is a full JavaFX example that shows a button that opens a FileChooser when it is clicked:

package tutorial.filechooser;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.scene.control.Button;

/**************************************************************************************************
 * @copyright 2023-2022
 * @package   tutorial.filechooser
 * @file      FileChooserExample.java
 * @date      2023-04-15 22:18
 * @author    qiao wei
 * @version   1.0
 * @brief     
 * @history
 *************************************************************************************************/
public class FileChooserExample extends Application {

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

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("JavaFX App");
        FileChooser fileChooser = new FileChooser();

        Button button = new Button("Select File");
        TextArea textArea = new TextArea("");

        VBox vBox = new VBox(button, textArea);
        Scene scene = new Scene(vBox, 960, 600);

        primaryStage.setScene(scene);
        
        final File[] selectedFile = {null};;
        button.setOnAction(e -> {
            selectedFile[0] = fileChooser.showOpenDialog(primaryStage);
            BufferedReader reader = null;
            
            try {
                reader = new BufferedReader(new FileReader(selectedFile[0]));
                int line = 1;
                
                StringBuilder stringBuilder = new StringBuilder();
                String tempString;
                while ((tempString = reader.readLine()) != null) {
                    // 顯示行號
//                    System.out.println("line " + line + ": " + tempString);
//                    line++;
                    stringBuilder.append(tempString + "\n");
                }
                
                textArea.setText(stringBuilder.toString());
                
                reader.close();
            } catch (IOException exception) {
                exception.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException exception) {
                    }
                }
            }
        });
        
        primaryStage.show();
    }
}

This example creates a full JavaFX application with a Button that when clicked opens a FileChooser . Notice how the primary Stage for the JavaFX application is passed as parameter to the FileChooser showOpenDialog() method.

Setting Initial Directory

You can set the initial directory displayed in the JavaFX FileChooser via its setInitialDirectory() method. Here is an example of setting the initial directory of a FileChooser dialog:

fileChooser.setInitialDirectory(new File("data"));

This example sets the initial directory displayed by the FileChooser to data.

Setting Initial File Name

You can set the initial file name to display in the FileChooser . Some platforms (e.g. Windows) may ignore this setting, though. Here is an example of setting the initial file name of a FileChooser:

fileChooser.setInitialFileName("myfile.txt");

This example sets the initial file name to myfile.txt .

Adding File Name Filters

It is possible to add file name filters to a JavaFX FileChooser. File name filters are used to filter out what files are shown in the FileChooser when the user browses around the file system. Here is an example of adding file name filters:

ileChooser fileChooser = new FileChooser();

fileChooser.getExtensionFilters().addAll(
     new FileChooser.ExtensionFilter("Text Files", "*.txt")
    ,new FileChooser.ExtensionFilter("HTML Files", "*.htm")
);

This examples adds two file name filters to the FileChooser. The user can choose between these file name filters inside the FileChooser dialog.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章