I have a simple JavaFX window with a TextField for users to enter a file path and a separate browse link.
JavaFX Window
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.
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
}
}
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.
Use showOpenDialog
or showSaveDialog
(depending on whether you want to open an existing file or save a new one). Both return a File
object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With