JFileChooser,想把它锁定到一个目录

Joa*_*sen 3 java jfilechooser

我有这个程序你可以下载文件,我希望JFileChooser被锁定到一个文件夹(目录),以便用户无法浏览其他任何内容.他只能从文件夹"C:\ Users\Thomas\Dropbox\Prosjekt RMI\SERVER \"中选择文件.我试过这么搜索但没找到任何东西.我的代码是:

String getProperty = System.getProperty("user.home");
JFileChooser chooser = new JFileChooser(getProperty + "/Dropbox/Prosjekt RMI/SERVER/"); //opens in the directory "//C:/Users/Thomas/Dropbox/Project RMI/SERVER/"
int returnVal = chooser.showOpenDialog(parent);
if (returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName());
Run Code Online (Sandbox Code Playgroud)

这工作正常,但现在我可以转到Project RMI文件夹,我不希望它这样做.

提前致谢 :)

编辑:我在你的帮助下做了什么:

JFileChooser chooser = new JFileChooser(getProperty + "/Dropbox/Project RMI/SERVER/"); 
                chooser.setFileView(new FileView() {
                    @Override
                    public Boolean isTraversable(File f) {
                        return (f.isDirectory() && f.getName().equals("SERVER")); 
                    }
                });
                int returnVal = chooser.showOpenDialog(parent);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    System.out.println("You chose to open this file: "
                            + chooser.getSelectedFile().getName());
                }
Run Code Online (Sandbox Code Playgroud)

dog*_*ane 6

设置 aFileView并覆盖该isTraversable方法,以便它仅对您希望用户看到的目录返回 true。

下面是一个例子:

String getProperty = System.getProperty("user.home");
final File dirToLock = new File(getProperty + "/Dropbox/Prosjekt RMI/SERVER/");
JFileChooser fc = new JFileChooser(dirToLock);
fc.setFileView(new FileView() {
    @Override
    public Boolean isTraversable(File f) {
         return dirToLock.equals(f);
    }
});
Run Code Online (Sandbox Code Playgroud)


And*_*son 5

创建一个自定义FileSystemView,将其用作接受FSV 的JFileChooser构造函数之一的参数.