JavaFX DirectoryChooser is more likely the same as the File Chooser in JavaFX, which will open a directory dialog to browse a folder. Sometimes when you are creating an application, you may need to let the user browse the computer’s file system’s directory path. Creating the DirectoryChooser is very easy, so in this tutorial, you will learn how to use the DirectoryChooser in JavaFX.
How to use the JavaFX DirectoryChooser
Directory Chooser is very helpful for developers to incorporate folder or directory selection functionality in JavaFX application. To create the DirectoryChooser, we need to use its DirectoryChooser class to create an object of DirectoryChooser in JavaFX. Please see the following example code below to learn more.
DirectoryChooser directoryChooser = new DirectoryChooser();
In order to use the JavaFX DirectoryChooser, you can call the showDialog() method to display a dialog box and select a directory from the file system of the computer. To do that, proceed to the example code below to learn more about it.
directoryChooser.showDialog(stage);
Another useful and important feature of the JavaFX DirectoryChooser is setting the dialog title and the initial directory. The setInitialDirectory() method allows the user to have easier and faster access to the most frequently used directories. Please proceed to the example code given below to learn more about setting custom dialog titles and initial directories.
directoryChooser.setTitle("Select Directory"); directoryChooser.setInitialDirectory(new File(System.getProperty("user.home")+"/Desktop"));
Now, the best part of using the DirectoryChooser is to get the selected directory. We need to use a File class and if statement to identify if the file is not null. Please see the example code below for the full code and learn more about how to use the JavaFX DirectoryChooser.
BorderPane layout = new BorderPane(); Button button = new Button("Select"); Label label = new Label(); layout.setTop(button); layout.setCenter(label); BorderPane.setAlignment(button, Pos.CENTER); BorderPane.setAlignment(label, Pos.CENTER); button.setOnAction(actionEvent -> { DirectoryChooser chooser = new DirectoryChooser(); chooser.setTitle("Select Directory"); chooser.setInitialDirectory(new File(System.getProperty("user.home")+"/Desktop")); File directory = chooser.showDialog(stage); if(directory != null){ label.setText(directory.toString()); } }); Scene scene = new Scene(layout, 320, 240); stage.setTitle("JavaFX Directory Chooser"); stage.setScene(scene); stage.show();