
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create File Chooser Using JavaFX
Using JavaFX file chooser, you can open files browse through them and save the files. The class javafx.stage.FileChooser represents a file chooser, you can open a file dialog open single or multiple files using this.
You can create a file chooser in your application by instantiating this class. This class has for properties −
initialDirectory − This property specifies the initial directory of the file chooser. You can set value to it using the setInitialDirectory() method.
selectedExtensionFilter − This property specifies the extension filter displayed in the dialog. You can set value to it using the setSelectedExtensionFilter() method.
Title − The property specifies the title of the dialog. can set value to it using the setTitle() method.
Once you instantiate the FileChooser class, set values to the required properties. You can, show a dialog in your file chooser to open a single file , open multiple files or, save a file by invoking showOpenDialog(), showOpenMultipleDialog() or, showSaveDialog() methods respectively.
Example
import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.paint.Color; import javafx.stage.FileChooser; import javafx.stage.Stage; import javafx.stage.FileChooser.ExtensionFilter; public class FileChooserExample extends Application { public void start(Stage stage) { //Creating a menu Menu fileMenu = new Menu("File"); //Creating menu Items MenuItem item = new MenuItem("Open Image"); fileMenu.getItems().addAll(item); //Creating a File chooser FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Open Image"); fileChooser.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*.*")); //Adding action on the menu item item.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent event) { //Opening a dialog box fileChooser.showOpenDialog(stage); }}); //Creating a menu bar and adding menu to it. MenuBar menuBar = new MenuBar(fileMenu); menuBar.setTranslateX(3); menuBar.setTranslateY(3); //Setting the stage Group root = new Group(menuBar); Scene scene = new Scene(root, 595, 355, Color.BEIGE); stage.setTitle("File Chooser Example"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }