sya*_*oom 3 java directory jfilechooser path
我有几个提供文件选择器的对话框。首先,我的编码是这样的
JFileChooser chooser= new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal= chooser.showOpenDialog(this);
if(returnVal==JFileChooser.APPROVE_OPTION){
File f= chooser.getSelectedFile();
jTextField1.setText(f.getPath());
chooser.setCurrentDirectory(f);
}
Run Code Online (Sandbox Code Playgroud)
就我而言,我想设置在下一个选择 JFileChooser 中选择作为默认路径的最后一个路径。对我来说有什么解决办法吗?感谢您的任何回复
根据您的要求,您可以使用首选项将其存储起来,并在程序重新启动后再次使用。
Preferences pref = Preferences.userRoot();
// Retrieve the selected path or use
// an empty string if no path has
// previously been selected
String path = pref.get("DEFAULT_PATH", "");
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// Set the path that was saved in preferences
chooser.setCurrentDirectory(new File(path));
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File f = chooser.getSelectedFile();
chooser.setCurrentDirectory(f);
// Save the selected path
pref.put("DEFAULT_PATH", f.getAbsolutePath());
}
Run Code Online (Sandbox Code Playgroud)
您必须“记住”最后一条路径。
通过将值存储在实例变量中可以轻松完成此操作...
private File lastPath;
//...
lastPath = f.getParentFile();
Run Code Online (Sandbox Code Playgroud)
当您需要时只需重置它...
//...
if (lastPath != null) {
chooser.setCurrentDirectory(lastPath);
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用 的单个实例JFileChooser,因此每次显示它时,它将位于上次使用的位置...