JavaFX | FileChooser Класс
Класс 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:
- 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 stageimportjavafx.application.Application;importjavafx.scene.Scene;importjavafx.scene.control.*;importjavafx.scene.layout.*;importjavafx.stage.Stage;importjavafx.geometry.*;importjavafx.scene.paint.*;importjavafx.scene.canvas.*;importjavafx.scene.text.*;importjavafx.scene.Group;importjavafx.scene.shape.*;importjavafx.event.ActionEvent;importjavafx.event.EventHandler;importjavafx.collections.*;importjava.io.*;importjavafx.stage.FileChooser;publicclassFileChooser_1extendsApplication {// launch the applicationpublicvoidstart(Stage stage){try{// set title for the stagestage.setTitle("FileChooser");// create a File chooserFileChooser fil_chooser =newFileChooser();// create a LabelLabel label =newLabel("no files selected");// create a ButtonButton button =newButton("Show open dialog");// create an Event HandlerEventHandler<ActionEvent> event =newEventHandler<ActionEvent>() {publicvoidhandle(ActionEvent e){// get the file selectedFile file = fil_chooser.showOpenDialog(stage);if(file !=null) {label.setText(file.getAbsolutePath()+" selected");}}};button.setOnAction(event);// create a ButtonButton button1 =newButton("Show save dialog");// create an Event HandlerEventHandler<ActionEvent> event1 =newEventHandler<ActionEvent>() {publicvoidhandle(ActionEvent e){// get the file selectedFile file = fil_chooser.showSaveDialog(stage);if(file !=null) {label.setText(file.getAbsolutePath()+" selected");}}};button1.setOnAction(event1);// create a VBoxVBox vbox =newVBox(30, label, button, button1);// set Alignmentvbox.setAlignment(Pos.CENTER);// create a sceneScene scene =newScene(vbox,800,500);// set the scenestage.setScene(scene);stage.show();}catch(Exception e) {System.out.println(e.getMessage());}}// Main Methodpublicstaticvoidmain(String args[]){// launch the applicationlaunch(args);}}Output:



 - 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 stageimportjavafx.application.Application;importjavafx.scene.Scene;importjavafx.scene.control.*;importjavafx.scene.layout.*;importjavafx.stage.Stage;importjavafx.geometry.*;importjavafx.scene.paint.*;importjavafx.scene.canvas.*;importjavafx.scene.text.*;importjavafx.scene.Group;importjavafx.scene.shape.*;importjavafx.event.ActionEvent;importjavafx.event.EventHandler;importjavafx.collections.*;importjava.io.*;importjavafx.stage.FileChooser;publicclassFileChooser_2extendsApplication {// launch the applicationpublicvoidstart(Stage stage){try{// set title for the stagestage.setTitle("FileChooser");// create a File chooserFileChooser fil_chooser =newFileChooser();// set titlefil_chooser.setTitle("Select File");// set initial Filefil_chooser.setInitialDirectory(newFile("e:\"));// create a LabelLabel label =newLabel("no files selected");// create a ButtonButton button =newButton("Show open dialog");// create an Event HandlerEventHandler<ActionEvent> event =newEventHandler<ActionEvent>() {publicvoidhandle(ActionEvent e){// get the file selectedFile file = fil_chooser.showOpenDialog(stage);if(file !=null) {label.setText(file.getAbsolutePath()+" selected");}}};button.setOnAction(event);// create a ButtonButton button1 =newButton("Show save dialog");// create an Event HandlerEventHandler<ActionEvent> event1 =newEventHandler<ActionEvent>() {publicvoidhandle(ActionEvent e){// get the file selectedFile file = fil_chooser.showSaveDialog(stage);if(file !=null) {label.setText(file.getAbsolutePath()+" selected");}}};button1.setOnAction(event1);// create a VBoxVBox vbox =newVBox(30, label, button, button1);// set Alignmentvbox.setAlignment(Pos.CENTER);// create a sceneScene scene =newScene(vbox,800,500);// set the scenestage.setScene(scene);stage.show();}catch(Exception e) {System.out.println(e.getMessage());}}// Main Methodpublicstaticvoidmain(String args[]){// launch the applicationlaunch(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.