Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get file path from JavaFX FileChooser?

I have a simple JavaFX window with a TextField for users to enter a file path and a separate browse link.

JavaFX Window

enter image description here

I'd like to ask how to extract the full file path of the selected file from JavaFX FileChooser (so I can set the path in the TextField)?

I understand what I'm trying to achieve can be done simply with Swing JFileChooser with something like:

JFileChooser chooser = new JFileChooser();
String someString = chooser.getSelectedFile().toString();

But since my application is in JavaFX I want it to have a consistent look and not a mix with Swing.

I've looked through the documentation, there doesn't seem to be a method for this https://docs.oracle.com/javase/8/javafx/api/javafx/stage/FileChooser.html

Thanks in advance.

like image 771
Hans Avatar asked Feb 17 '16 08:02

Hans


3 Answers

In the controller class where you have the TextField you can create a method like so:

public void getTheUserFilePath() {

    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Upload File Path");
    fileChooser.getExtensionFilters().addAll(
            new FileChooser.ExtensionFilter("ALL FILES", "*.*"),
            new FileChooser.ExtensionFilter("ZIP", "*.zip"),
            new FileChooser.ExtensionFilter("PDF", "*.pdf"),
            new FileChooser.ExtensionFilter("TEXT", "*.txt"),
            new FileChooser.ExtensionFilter("IMAGE FILES", "*.jpg", "*.png", "*.gif")
    );


    File file = fileChooser.showOpenDialog(dialogPane.getScene().getWindow());

    if (file != null) {
        // pickUpPathField it's your TextField fx:id
        pickUpPathField.setText(file.getPath());

    } else  {
        System.out.println("error"); // or something else
    }

}
like image 28
Marinel P Avatar answered Oct 06 '22 00:10

Marinel P


Here's another documentation. What you get in return from using showOpenDialog is a File object.

public File showOpenDialog(Window ownerWindow)

Shows a new file open dialog. The method doesn't return until the displayed open dialog is dismissed. The return value specifies the file chosen by the user or null if no selection has been made. If the owner window for the file dialog is set, input to all windows in the dialog's owner chain is blocked while the file dialog is being shown.

A file object has various methods like e. g. getAbsolutePath.

like image 82
Roland Avatar answered Oct 05 '22 22:10

Roland


Use showOpenDialog or showSaveDialog (depending on whether you want to open an existing file or save a new one). Both return a File object.

like image 21
Itai Avatar answered Oct 06 '22 00:10

Itai