了解 JFileChooser 行为

Understanding JFileChooser behaviour

我正在尝试打开一个 JFileChooser 对话框让用户决定他希望的目录以进行后续操作。

以下是我当前的代码:

JFileChooser chooser;
if(pref.get("LAST_PATH", "") != null){
    chooser = new JFileChooser(pref.get("LAST_PATH", ""));
} else{
    chooser = new JFileChooser(home_dir);
}
//chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
int retVal = chooser.showOpenDialog(frame);
System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory().toString());

home_dir 是指向用户下载目录的静态字符串。

我不理解的行为:

home_dir = C:/Users/Scy/Downloads

不选择任何文件(或目录)按确定

Output: C:/Users/Scy

home_dir = C:/Users/Scy/Downloads

Select 下载中的任何文件

Output: C:/Users/Scy/Downloads

为什么我没有选择任何东西,只是按确定,却没有得到完整路径 (C:/Users/Scy/Downloads) 作为输出? (激活 DIRECTORIES_ONLY 后,如果没有 DIRECTORIES_ONLY,则无法在不选择任何内容的情况下按 OK)

编辑:我刚刚注意到,当我在没有选择任何东西的情况下按下取消按钮时,输出确实是我所期望的,C:/Users/Scy/Downloads

根据对此 post 的回答,我尝试了以下方法:

JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File(home_dir)); //home_dir = "C:/Users/Scy/Downloads"

结果和上面一模一样。按取消按钮会导致完整路径输出,而按 OK/Accept 会导致 C:/Users/Scy.

也许 'selected file'(或目录)在 'current directory'(您正在检索 atm。)中?

如果你想要当前选择的文件,chooser.getSelectedFile()就是你要找的。请记住,当切换到 DirectoryOnly 模式时,此方法将 return 目录(例如,代表目录的 File 实例)。

方法chooser.getCurrentDirectory() 将return 当前所选文件的父目录,这说明了意外的结果。 (getSelectedFile.getParentFile() 很可能 return 同一个文件)


如果您尝试检索父目录,则您设置的起始目录不正确。请注意您是如何在第一个构造函数中传递选定文件的?这意味着在第二个构造函数中 'home_dir' 将成为选定的文件。如果只想将 'home_dir' 设置为起始目录,则应使用无参数构造函数并改为调用 chooser.setCurrentDirector(new File(home_dir))。这是您的代码的片段:

JFileChooser chooser;
if(pref.get("LAST_PATH", "") != null){
    // set last SELECTED file/directory path.
    chooser = new JFileChooser(pref.get("LAST_PATH", ""));
 } else{
     // set currentDirectory,  but dont select anything yet.
     chooser = new JFileChooser();
     chooser.setCurrentDirectory(new File(home_dir));
}

getCurrentDirectory() returns a directory name, not a file name. If the user selects a file, this method returns the name of the directory which contains that file. If you want the name of the file which was selected, you should use getSelectedFile(). If you haven't yet, you should read this Oracle tutorial on file choosers.