JFileChooser.FILES_ONLY getting both files and directories

350 views Asked by At

I am trying to use JFileChooser to only select files eliminating any directories in the folder:

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

However, I am getting both files and directories. This seems pretty straight forward. What have I missed?

enter image description here

3

There are 3 answers

1
Till Hemmerich On BEST ANSWER

Sorry had to rewrite it some times my mind trolls me while explaining.

Okay so you think that setting your FileSelectionMode to FILES_ONLY will make your JFileChooser only display files and wont show directories anymore. But what actually happens is it will no longer let you select a directories as an input. this is to ensure you are getting a file when you expect it to.

BUT. Since it would be discustingly unhandy to navigate without seeing Directories they are still getting displayed and you can go into them(of cause)

Same goes for direcotries_only this will still show you files but you cant select them as input.

0
Dominik Kunicki On

JFileChooser.FILES_ONLY flag indicates that you can only select files. Directories are shown because user may want to find file inside them.

If you want to exclude directories from view use FileFilter

fc.setFileFilter(new FileFilter() {

        @Override
        public String getDescription() {
            return "Only files";
        }

        @Override
        public boolean accept(File f) {
            return !f.isDirectory();
        }
    });
1
Maxim On

Seems like you want to hide directories. So, just create custom 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();
    }
});

As you can see I leave only files in getFiles method and now I see only files in my home directory:

hide directories in home directory