Single Root File Chooser
Posted by Rob Camick on January 28, 2009
The JFileChooser component allows a user to select a file from anywhere in the File System. The “Look In” combo box allows you to move around the File System easily to find the file you are looking for. However, there may be times when you want to restrict the user to searching a specific directory tree. Therefore, we need to control the entries displayed in the “Look In” combo box.
As the API says, FileSystemView is JFileChooser’s gateway to the file system. The SingleRootFileSystemView class is a customized view of the file system that lets the file chooser only see the files contained in the specified directory (and its sub directories). The “Look In” combo box will now only display the specifed directory, and its children as you navigate the directory tree. In addition, the “Up One Level” button on the file chooser will be disabled when viewing files at the specified root directory to prevent navigation to the parent of the directory.
To limit the file chooser to search the files in my Java JDK I used:
File root = new File("c:/java/jdk6.7");
FileSystemView fsv = new SingleRootFileSystemView( root );
JFileChooser chooser = new JFileChooser(fsv);
After selecting the “docs” directory, the file chooser would look like:
This class was designed to be used once. That is, if you ever need to change the root directory of the view you should create a new SingleRootFileSystemView class and a new JFileChooser. I recommend this approach because the setFileSystemView(…) does not work as expected. However, it appears that the following work around will allow you to dynamically change the file system view:
File root2 = new File("c:/java/blog");
FileSystemView fsv2 = new SingleRootFileSystemView( root2 );
I normally don’t ever recommend using the updateUI() method as this should only be used for a Look and Feel change. Use this approach at your own risk.