[英]How do I restrict JFileChooser to a directory?
I want to limit my users to a directory and its sub directories but the "Parent Directory" button allows them to browse to an arbitrary directory. 我想将用户限制在目录及其子目录中,但“父目录”按钮允许他们浏览到任意目录。
How should I go about doing that? 我应该怎么做呢?
Incase anyone else needs this in the future: 其他人在将来需要这个:
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;
}
}
You'll obviously need to make a better "createNewFolder" method, but this does restrict the user to one of more directories. 您显然需要创建一个更好的“createNewFolder”方法,但这会将用户限制为一个或多个目录。
And use it like this: 并像这样使用它:
FileSystemView fsv = new DirectoryRestrictedFileSystemView(new File("X:\\"));
JFileChooser fileChooser = new JFileChooser(fsv);
or like this: 或者像这样:
FileSystemView fsv = new DirectoryRestrictedFileSystemView( new File[] {
new File("X:\\"),
new File("Y:\\")
});
JFileChooser fileChooser = new JFileChooser(fsv);
您可以通过设置自己的FileSystemView来完成此操作。
The solution of Allain is almost complete. Allain的解决方案几乎已经完成。 Three problems are open to solve:
有三个问题可以解决:
public TFile getHomeDirectory() { return rootDirectories[0]; }
set class and constructor public
设置类和构造函数
public
Change JFileChooser fileChooser = new JFileChooser(fsv);
更改
JFileChooser fileChooser = new JFileChooser(fsv);
into JFileChooser fileChooser = new JFileChooser(fsv.getHomeDirectory(),fsv);
进入
JFileChooser fileChooser = new JFileChooser(fsv.getHomeDirectory(),fsv);
I use it for restricting users to stay in a zip-file via TrueZips TFileChooser and with slight modifications to the above code, this works perfectly. 我使用它来限制用户通过TrueZips TFileChooser保留一个zip文件,稍微修改上面的代码,这非常有效。 Thanks a lot.
非常感谢。
No need to be that complicated. 不需要那么复杂。 You can easily set selection mode of a JFileChooser like this
您可以像这样轻松设置JFileChooser的选择模式
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setMultiSelectionEnabled(false);
You can read more reference here How to Use File Choosers 您可以在此处阅读更多参考如何使用文件选择器
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.