0

I'm using JFileChooser to open up a dialog box for a user to open a file. I've already set the current directory if the user actually selects a file:

int returnVal = fc.showOpenDialog(frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
    File newfile = fc.getSelectedFile();

    //set the default directory to this file's directory
    fc.setCurrentDirectory(newfile.getParentFile());
}
else {
    //User cancels file chooser. How to still set the current directory
    //to the one they were last in?
}

However, even if the user cancels the dialog box (e.g. they decide they want to do something else in the program before choosing a file), I want to save the last directory they were in so they avoid the hassle of finding that directory again. Is this possible at all?

shimizu
  • 998
  • 14
  • 20
  • Use the same file chooser instance and the size, file filter and directory should always stay the same. – Andrew Thompson May 12 '14 at 21:26
  • You can also create another class that extends `JFileChooser` and override the method that runs when user cancels – SomethingSomething May 12 '14 at 21:32
  • I am using the same file chooser instance throughout. If the user actually selects the file, then subsequent times that I pull up the dialog box it will be in the right directory. But I'm wondering if the first time the user opens up the dialog box if the file chooser captures the last directory it was in before the user cancels. – shimizu May 12 '14 at 21:39
  • Does this answer your question? [Is there any way to make Java file selection dialogs remember the last directory?](https://stackoverflow.com/questions/8282048/is-there-any-way-to-make-java-file-selection-dialogs-remember-the-last-directory) – Mahozad Sep 27 '22 at 19:13

1 Answers1

3

This is because an instance of JFileChooser "remembers" it's last location. You could create a new instance each time you want to show the dialog, but that's inefficient and can be time consuming

Instead, save the last "good" location in some kind of instance variable. Before you show the save dialog, set its current directory, passing the last known "good" location

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • How specifically do you get JFileChooser's last location if the user cancels the dialog box? – shimizu May 12 '14 at 21:36
  • You just did. You can use getCurrentDirectory or ten selected File's parent refernce – MadProgrammer May 12 '14 at 21:39
  • Oh I see, I didn't realize that getCurrentDirectory would know its last location even if the dialog was cancelled. It works now. Thanks! – shimizu May 12 '14 at 21:42