JavaFX | FileChooser Класс

Опубликовано: 12 Февраля, 2022

Класс FileChooser является частью JavaFX. Он используется для вызова диалогов открытия файлов для выбора одного файла (showOpenDialog), диалогов открытия файлов для выбора нескольких файлов (showOpenMultipleDialog) и диалогов сохранения файлов (showSaveDialog). Класс FileChooser наследует класс Object.

Конструкторами класса являются:

  • FileChooser () : создает новый диалог FileChooser.

Часто используемые методы:

Метод Объяснение
getInitialDirectory () Возвращает начальный каталог средства выбора файла.
getTitle () Возвращает заголовок средства выбора файла.
setInitialDirectory (файл f) Устанавливает начальный каталог средства выбора файлов.
setTitle (Строка t) Устанавливает заголовок средства выбора файла.
showOpenDialog (Окно w) Показывает новый диалог выбора открытого файла.
setInitialFileName (строка n) Устанавливает имя исходного файла для средства выбора файлов.
showSaveDialog (Окно w) Показывает новое диалоговое окно выбора файла для сохранения.
getInitialFileName () Возвращает начальное имя файла средства выбора файла.

Below programs illustrate the use of FileChooser Class:

  1. Java Program to create fileChooser and add it to the stage: In this program we will create a file chooser named file_chooser. Then create a Label named label and two Buttons named button and button1. We will create two EventHandler to handle the events when the button or button1 pressed. When the button is pressed, an open file chooser dialog appears and the selected file is shown as text in the label and when button1 is pressed, a save file chooser appears and the selected file is shown as text in the label. Add the label and the button to Vbox and add the VBox to the Scene and add the scene to the stage, and call the show() function to display the final results.
    // Java Program to create fileChooser
    // and add it to the stage
    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.*;
    import javafx.scene.layout.*;
    import javafx.stage.Stage;
    import javafx.geometry.*;
    import javafx.scene.paint.*;
    import javafx.scene.canvas.*;
    import javafx.scene.text.*;
    import javafx.scene.Group;
    import javafx.scene.shape.*;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.collections.*;
    import java.io.*;
    import javafx.stage.FileChooser;
       
    public class FileChooser_1 extends Application {
       
    // launch the application
    public void start(Stage stage)
    {
      
        try {
      
            // set title for the stage
            stage.setTitle("FileChooser");
      
            // create a File chooser
            FileChooser fil_chooser = new FileChooser();
      
            // create a Label
            Label label = new Label("no files selected");
      
            // create a Button
            Button button = new Button("Show open dialog");
      
            // create an Event Handler
            EventHandler<ActionEvent> event = 
            new EventHandler<ActionEvent>() {
      
                public void handle(ActionEvent e)
                {
      
                    // get the file selected
                    File file = fil_chooser.showOpenDialog(stage);
      
                    if (file != null) {
                          
                        label.setText(file.getAbsolutePath() 
                                            + "  selected");
                    }
                }
            };
      
            button.setOnAction(event);
      
            // create a Button
            Button button1 = new Button("Show save dialog");
      
            // create an Event Handler
            EventHandler<ActionEvent> event1 = 
             new EventHandler<ActionEvent>() {
      
                public void handle(ActionEvent e)
                {
      
                    // get the file selected
                    File file = fil_chooser.showSaveDialog(stage);
      
                    if (file != null) {
                        label.setText(file.getAbsolutePath() 
                                            + "  selected");
                    }
                }
            };
      
            button1.setOnAction(event1);
      
            // create a VBox
            VBox vbox = new VBox(30, label, button, button1);
      
            // set Alignment
            vbox.setAlignment(Pos.CENTER);
      
            // create a scene
            Scene scene = new Scene(vbox, 800, 500);
      
            // set the scene
            stage.setScene(scene);
      
            stage.show();
        }
      
        catch (Exception e) {
      
            System.out.println(e.getMessage());
        }
    }
      
    // Main Method
    public static void main(String args[])
    {
      
        // launch the application
        launch(args);
    }
    }

    Output:

  2. Java Program to create FileChooser, set title, initial File and add it to the stage: In this program we will create a file chooser named fil_chooser . Then create a Label named label and two Buttons named button and button1. Set the title and initial directory of file chooser using the setTitle() and setInitialDirectory() function. Now create two EventHandler to handle the events when the button or button1 pressed. When the button is pressed, an open file chooser dialog appears and the selected file is shown as text in the label and when button1 is pressed, a save file chooser appears and the selected file is shown as text in the label. Add the label and the button to Vbox and add the VBox to the Scene and add the scene to the stage, and call the show() function to display the final results.
    // Java Program to create FileChooser
    // & set title, initial File
    // and add it to the stage
    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.*;
    import javafx.scene.layout.*;
    import javafx.stage.Stage;
    import javafx.geometry.*;
    import javafx.scene.paint.*;
    import javafx.scene.canvas.*;
    import javafx.scene.text.*;
    import javafx.scene.Group;
    import javafx.scene.shape.*;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.collections.*;
    import java.io.*;
    import javafx.stage.FileChooser;
       
    public class FileChooser_2 extends Application {
      
    // launch the application
    public void start(Stage stage)
    {
      
        try {
      
            // set title for the stage
            stage.setTitle("FileChooser");
      
            // create a File chooser
            FileChooser fil_chooser = new FileChooser();
      
            // set title
            fil_chooser.setTitle("Select File");
      
            // set initial File
            fil_chooser.setInitialDirectory(new File("e:\"));
      
            // create a Label
            Label label = new Label("no files selected");
      
            // create a Button
            Button button = new Button("Show open dialog");
      
            // create an Event Handler
            EventHandler<ActionEvent> event = 
            new EventHandler<ActionEvent>() {
      
                public void handle(ActionEvent e)
                {
      
                    // get the file selected
                    File file = fil_chooser.showOpenDialog(stage);
      
                    if (file != null) {
                        label.setText(file.getAbsolutePath() 
                                            + "  selected");
                    }
                }
            };
      
            button.setOnAction(event);
      
            // create a Button
            Button button1 = new Button("Show save dialog");
      
            // create an Event Handler
            EventHandler<ActionEvent> event1 = 
             new EventHandler<ActionEvent>() {
      
                public void handle(ActionEvent e)
                {
      
                    // get the file selected
                    File file = fil_chooser.showSaveDialog(stage);
      
                    if (file != null) {
                        label.setText(file.getAbsolutePath() 
                                            + "  selected");
                    }
                }
            };
      
            button1.setOnAction(event1);
      
            // create a VBox
            VBox vbox = new VBox(30, label, button, button1);
      
            // set Alignment
            vbox.setAlignment(Pos.CENTER);
      
            // create a scene
            Scene scene = new Scene(vbox, 800, 500);
      
            // set the scene
            stage.setScene(scene);
      
            stage.show();
        }
      
        catch (Exception e) {
      
            System.out.println(e.getMessage());
        }
    }
      
    // Main Method
    public static void main(String args[])
    {
      
        // launch the application
        launch(args);
    }
    }

    Output:

Note: The above programs might not run in an online IDE please use an offline compiler.

Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/stage/FileChooser.html

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.