7

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.

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
Hans
  • 121
  • 1
  • 1
  • 8

3 Answers3

7

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.

Roland
  • 18,114
  • 12
  • 62
  • 93
6

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

Itai
  • 6,641
  • 6
  • 27
  • 51
  • Thanks so much for your help. Will note that 'showSaveDialog' works also. – Hans Feb 17 '16 at 08:55
  • 1
    @Hans: `showSaveDialog` is likely not what you want in this case, since it allows the user to *"create a new file"* (i.e. the file returned may not exist). – fabian Feb 17 '16 at 11:29
2

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
    }

}
Marinel P
  • 41
  • 5