我想将用户限制在目录及其子目录中,但“父目录”按钮允许他们浏览到任意目录。
我应该怎么做呢?
答案 0 :(得分:22)
将来其他任何人都需要这个:
class DirectoryRestrictedFileSystemView extends FileSystemView
{
private final File[] rootDirectories;
DirectoryRestrictedFileSystemView(File rootDirectory)
{
this.rootDirectories = new File[] {rootDirectory};
}
DirectoryRestrictedFileSystemView(File[] rootDirectories)
{
this.rootDirectories = rootDirectories;
}
@Override
public File createNewFolder(File containingDir) throws IOException
{
throw new UnsupportedOperationException("Unable to create directory");
}
@Override
public File[] getRoots()
{
return rootDirectories;
}
@Override
public boolean isRoot(File file)
{
for (File root : rootDirectories) {
if (root.equals(file)) {
return true;
}
}
return false;
}
}
您显然需要制作更好的“createNewFolder”方法,但这会将用户限制为其中一个目录。
并像这样使用它:
FileSystemView fsv = new DirectoryRestrictedFileSystemView(new File("X:\\"));
JFileChooser fileChooser = new JFileChooser(fsv);
或者像这样:
FileSystemView fsv = new DirectoryRestrictedFileSystemView( new File[] {
new File("X:\\"),
new File("Y:\\")
});
JFileChooser fileChooser = new JFileChooser(fsv);
答案 1 :(得分:12)
您可以通过设置自己的FileSystemView来完成此操作。
答案 2 :(得分:5)
Allain的解决方案几乎完成了。有三个问题可以解决:
public TFile getHomeDirectory()
{
return rootDirectories[0];
}
设置类和构造函数public
将JFileChooser fileChooser = new JFileChooser(fsv);
更改为JFileChooser fileChooser = new JFileChooser(fsv.getHomeDirectory(),fsv);
我用它来限制用户通过TrueZips TFileChooser保留一个zip文件,稍微修改上面的代码,这非常有效。非常感谢。
答案 3 :(得分:-1)
不需要那么复杂。你可以像这样轻松设置JFileChooser的选择模式
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setMultiSelectionEnabled(false);
您可以在此处阅读更多参考资料How to Use File Choosers