有没有办法让java文件选择对话框记住最后一个目录?

使用java应用程序时,每次打开对话框时,起始目录始终是我的主目录。 有没有办法让它记住上次使用的目录? 或者,是否有“改进的”java文件选择对话框,允许类型到搜索或大多数其他应用程序文件选择对话框中标准的任何function?

编辑:我认为发布的答案解决了编写 Java应用程序的问题,但不适用于用户。 也许用户不可能更改文件浏览器界面,但我想知道这一点。 如果它很重要,我会考虑一些具体的例子(亚马逊AWS上传器),但我观察到大多数使用文件浏览器的java应用程序中的行为。

将文件选择器存储为类属性。 重新打开时,将保留以下内容。

  1. 目录。
  2. 目录中用户滚动位置的位置。
  3. 选定的文件filter。
  4. 尺寸。
  5. 屏幕上的位置。
  6. PLAF。
  7. ..

有没有办法让它记住上次使用的目录?

当然,如果您的意思是在运行之间保持状态则存在许多存储细节的替代forms,以及存储它们的位置/方式。 有关使用Properties文件存储JFrame边界的示例,请参阅此答案 。


也许用户无法更改文件浏览器界面,..

‘用户’是什么? 你是指在应用程序中使用一个的开发人员吗?

也许您需要的是实现自己的文件选择器。 如果是这种情况,您可以从FileBro代码开始。

JFileChooser不记得了。 但是,Java提供了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()); } 

Swing JFileChooser有一个设置初始目录的方法。 setCurrentDirectory(File dir)选择文件后,您可以通过调用getCurrentDirectory获取所选目录,并将其存储在应用程序的某个配置文件中。

您可以在应用程序中缓存最后一个目录位置,并在打开文件选择器时通过setCurrentDirectory指定默认位置

在这里,我使用带有目录对话框的简单代码打开最后一个使用目录

 IDialogSettings dialogSettings = Activator.getDefault().getDialogSettings(); String lastUsedPath = dialogSettings.get(IAntUIConstants.DIALOGSTORE_LASTANTHOME); if (lastUsedPath == null) { lastUsedPath = "c:\\"; } DirectoryDialog dialog = new DirectoryDialog(Display.getDefault().getActiveShell()); dialog.setFilterPath(lastUsedPath); String location = dialog.open(); if (location == null) { return; } dialogSettings.put(IAntUIConstants.DIALOGSTORE_LASTANTHOME, location); AntCorePreferences preferences = AntCorePlugin.getPlugin().getPreferences(); String defaultHome = preferences.getAntHome(); if (location.equalsIgnoreCase(defaultHome)) { location = null; }