How to get file path from JavaFX FileChooser?

Hans picture Hans · Feb 17, 2016 · Viewed 19.5k times · Source

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.

Answer

Itai picture Itai · Feb 17, 2016

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