4

I am using JavaFX. I would like to start a FileChooser from the directory of the program, the initial repository should therefore be that of the program.

Here is my FileChooser declaration:

FileChooser chooser = new FileChooser();
chooser.getExtensionFilters().addAll(
new ExtensionFilter("Text Files", "*.txt"),
new ExtensionFilter("All Files", "*.*"));
chooser.setTitle("Choisir un fichier");
file = chooser.showOpenDialog(new Stage());

How can I do that?

AbdelKh
  • 499
  • 7
  • 19
  • this question is already answered [here](http://stackoverflow.com/questions/32318974/javafx-filechooser-initial-directory). You can also check [the java doc](https://docs.oracle.com/javase/8/javafx/api/javafx/stage/FileChooser.html). The method you are looking for is setInitialDirectory(File value). – alvaro May 16 '17 at 14:17
  • It was not. The answer you're giving tells how to set the user's directory as the initial directory. That's not my question. – AbdelKh May 16 '17 at 14:28
  • What does "the directory of the program" mean? – James_D May 16 '17 at 14:51
  • The directory where the executable program file reside. – AbdelKh May 16 '17 at 14:55
  • http://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running-jar-file ??? – fabian May 16 '17 at 15:52
  • Easy as hell. I thougth you could guess. The dir is "." – alvaro May 17 '17 at 07:25

1 Answers1

6

The current dir is ".". Here is how you can do that:

FileChooser chooser = new FileChooser();
String currentPath = Paths.get(".").toAbsolutePath().normalize().toString();
chooser.setInitialDirectory(new File(currentPath));
chooser.showOpenDialog(new Stage());

Edit: the Stage or javafx Node you should be passing to the FileChooser is the one you want to be its parent.

alvaro
  • 452
  • 5
  • 13