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?
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()
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.
Override the approveSelection() method. Something like:
JFileChooser chooser = new JFileChooser( new File(".") )
{
public void approveSelection()
{
if (getSelectedFile().isFile())
{
// beep
return;
}
else
super.approveSelection();
}
};
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);
}
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 );