JChooser:限制视图并添加到特定目录树

时间:2014-03-24 18:13:14

标签: java swing user-interface jfilechooser

这是之前提出的问题,但该解决方案中存在错误。
我的要求是 - 当用户调用JFileChooser时,他应该无法向上导航。

答案是编写自定义FileSystemView - How do I restrict JFileChooser to a directory? 有一个解决方案,就像 http://tips4java.wordpress.com/2009/01/28/single-root-file-chooser/

然而,他们两个有时都有问题。为了正确实现,FileChooser应该显示为 -

enter image description here

然而,有时,它看起来像 - enter image description here

并且用户必须单击向上箭头才能看到正确的目录。知道为什么会这样吗?一个解决方案?

自定义FileSystemView的代码是

    public class SingleRootFileSystemView extends FileSystemView
{
    File root;
    File[] roots = new File[1];

    public SingleRootFileSystemView(File root)
    {
        super();
        this.root = root;
        roots[0] = root;
    }

    @Override
    public File createNewFolder(File containingDir)
    {
        File folder = new File(containingDir, "New Folder");
        folder.mkdir();
        return folder;
    }

    @Override
    public File getDefaultDirectory()
    {
        return root;

    }

    @Override
    public File getHomeDirectory()
    {
        return root;

    }

    @Override
    public File[] getRoots()
    {
        return roots;
    }
    }

调用它的代码是

FileSystemView fsv = new SingleRootFileSystemView(folder);
JFileChooser fileChooser = new JFileChooser(fsv.getHomeDirectory(),fsv);
fileChooser.setFileSelectionMode(1);
int returnVal = fileChooser.showOpenDialog(null);

非常感谢。

0 个答案:

没有答案