Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to make java file selection dialogs remember the last directory?

Tags:

java

swing

When using java applications, every time I open a dialog box, the starting directory is always my home directory. Is there any way to make it remember the last used directory? Alternately, are there 'improved' java file selection dialogs that allow type-to-search or any of the features that are standard in most other application file selection dialogs?

EDIT: I think the answers posted address the question for writing java applications, but not for a user. Perhaps it's not possible for the user to change the file browser interface, but I'd like to know that. In case it matters, I have a few specific examples in mind (Amazon AWS uploader) but I have observed that behavior in most java applications that use a file browser.

like image 959
keflavich Avatar asked Nov 26 '11 22:11

keflavich


2 Answers

JFileChooser does not remember it. However, Java provides a Preferences API

Preferences prefs = Preferences.userRoot().node(getClass().getName());
JFileChooser chooser = new JFileChooser(prefs.get(LAST_USED_FOLDER,
    new File(".").getAbsolutePath()));
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
    // do something
    prefs.put(LAST_USED_FOLDER, chooser.getSelectedFile().getParent());
}
like image 158
Archimedes Trajano Avatar answered Sep 29 '22 08:09

Archimedes Trajano


Store the file chooser as a class attribute. When it is re-opened, the following will be preserved.

  1. The directory.
  2. The place in the directory to where the user had scrolled.
  3. The selected file filter.
  4. The size.
  5. The location on screen.
  6. The PLAF.
  7. ..

Is there any way to make it remember the last used directory?

Of course, if you mean persist the state between runs, there are a number of alternative forms of storing the details, and places/ways to store them. See this answer for an example of storing the bounds of a JFrame using a Properties file.


Perhaps it's not possible for the user to change the file browser interface, ..

What 'user'? Do you mean the developer who uses one in an app.?

Maybe what you need is to implement your own file chooser. If that is the case, you might start with the FileBro code.

like image 30
Andrew Thompson Avatar answered Sep 29 '22 08:09

Andrew Thompson