views:

319

answers:

5

I feel like there should be a simple way to do this but I can't figure it out. I have a JFileChooser that allows the user to select directories. I want to show all the files in the directories to give the user some context, but only directories should be accepted as selections (maybe the Open button would be disabled when a file is selected). Is there an easy way of doing this?

A: 

AFAIK JFileChooser separates file filtering (what can be viewed, very configurable) from selection filtering (what can be chosen).

The configuration of selection filtering is much more limited, but AFAIK you can choose to allow only dirs or only files to be selected with setFileSelectionMode()

Uri
A: 

I think the best solution is just to allow the user to select either a file or a directory. And if the user select a file just use the directory where that file is located.

Martin Tilsted
+3  A: 

Override the approveSelection() method. Something like:

JFileChooser chooser = new JFileChooser( new File(".") )
{
    public void approveSelection()
    {
        if (getSelectedFile().isFile())
        {
            // beep
            return;
        }
        else
            super.approveSelection();
    }
};
camickr
A: 

See setFileSelectionMode() in How to Use File Choosers:

setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)

Addendum: The effect can be see by uncommenting line 73 of this demo, but it appears to be platform-dependent.

Addendum: If using FILES_AND_DIRECTORIES, consider changing the button text accordingly:

chooser.setApproveButtonText("Choose directory");

Also, consider using DIRECTORIES_ONLY on platforms that already meet your UI requirements:

if (System.getProperty("os.name").startsWith("Mac OS X")) {
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
} else {
    chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
}
trashgod
But that will hide files, which is what he doesn't want.
Michael Myers
@mmyers: It shows the files in gray in the example cited above. YMMV
trashgod
From what the tutorial says, it seems it's laf-dependent.
Michael Myers
trashgod
+1  A: 

My solution is a merge between the answers of camickr and trashgod:

    final JFileChooser chooser = new JFileChooser() {
            public void approveSelection() {
                if (getSelectedFile().isFile()) {
                    return;
                } else
                    super.approveSelection();
            }
    };
    chooser.setFileSelectionMode( JFileChooser.FILES_AND_DIRECTORIES );
ablaeul
+1 Looks like I'm in good company! I updated my answer to reflect this combined approach.
trashgod