我正在尝试使用JFileChooser来只选择文件来删除文件夹中的任何目录:
fc.setFileSelectionMode(JFileChooser.FILES_ONLY); // Only look at files
fc.setCurrentDirectory(new File(dbPath));
int returnVal = fc.showOpenDialog(null); // Switch DB dialog
if (returnVal == JFileChooser.APPROVE_OPTION) // Get good DB?
{
filePDF = fc.getSelectedFile().getAbsolutePath(); // Get path
txtTSDir.setText(filePDF);
}
else
但是,我得到了文件和目录。这看起来非常简单。我错过了什么?
答案 0 :(得分:2)
好像你想要隐藏目录。因此,只需创建自定义FileSystemView
:
JFileChooser jFileChooser = new JFileChooser();
jFileChooser.setFileSystemView(new FileSystemView() {
@Override
public File[] getFiles(File dir, boolean useFileHiding) {
return Arrays.stream(super.getFiles(dir, useFileHiding)).filter(File::isFile).toArray(File[]::new);
}
@Override
public File createNewFolder(File containingDir) throws IOException {
throw new NotImplementedException();
}
});
正如您所看到的,我只保留getFiles
方法中的文件,现在我只看到主目录中的文件:
答案 1 :(得分:0)
抱歉不得不重写它有时我的思绪在解释时哄我。
好的,所以你认为将FileSelectionMode设置为FILES_ONLY会使你的JFileChooser只显示文件而不再显示目录。 但实际发生的是它将不再允许您选择目录作为输入。 这是为了确保您在预期时获得文件。
BUT。 因为在没有看到目录的情况下进行导航会非常不方便,所以他们仍然会显示出来并且你可以进入它们(原因)
同样适用于direcotries_only这仍会显示文件,但你不能选择它们作为输入。
答案 2 :(得分:0)
JFileChooser.FILES_ONLY标志表示您只能选择文件。显示目录是因为用户可能想要在其中查找文件。
如果要从视图中排除目录,请使用FileFilter
fc.setFileFilter(new FileFilter() {
@Override
public String getDescription() {
return "Only files";
}
@Override
public boolean accept(File f) {
return !f.isDirectory();
}
});