How to create a File Chooser using JavaFX?

JavaFXObject Oriented ProgrammingProgramming

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.


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");
      //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
      //Creating a menu bar and adding menu to it.
      MenuBar menuBar = new MenuBar(fileMenu);
      //Setting the stage
      Group root = new Group(menuBar);
      Scene scene = new Scene(root, 595, 355, Color.BEIGE);
      stage.setTitle("File Chooser Example");
   public static void main(String args[]){


Updated on 18-May-2020 07:35:41