[英]How to set the last path as the next default using JFileChooser
我有几个提供文件选择器的对话框。 首先,我的编码是这样的
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);
}
就我而言,我想设置下一个选择JFileChooser中的默认路径作为默认路径。 有什么解决办法吗? 感谢您的任何回复
您将必须“记住”最后一条路径。
通过将值存储在实例变量中,可以轻松完成此操作。
private File lastPath;
//...
lastPath = f.getParentFile();
只需在需要时将其重置...
//...
if (lastPath != null) {
chooser.setCurrentDirectory(lastPath);
}
您还可以使用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());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.