Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top