Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I restrict JFileChooser to a directory?

Tags:

I want to limit my users to a directory and its sub directories but the "Parent Directory" button allows them to browse to an arbitrary directory.

How should I go about doing that?

like image 953
Allain Lalonde Avatar asked Aug 28 '08 15:08

Allain Lalonde


People also ask

How do I select multiple files in JFileChooser?

JFileChooser. setMultiSelectionEnabled(true) − To enable the multiple selection of file.

How do I get files from JFileChooser?

JFileChooser has a method, getSelectedFile(). Which is a File. If you open the dialog with showSaveDialog() you should be able to get the File from that (file. getName()).


2 Answers

Incase anyone else needs this in the future:

class DirectoryRestrictedFileSystemView extends FileSystemView {     private final File[] rootDirectories;      DirectoryRestrictedFileSystemView(File rootDirectory)     {         this.rootDirectories = new File[] {rootDirectory};     }      DirectoryRestrictedFileSystemView(File[] rootDirectories)     {         this.rootDirectories = rootDirectories;     }      @Override     public File createNewFolder(File containingDir) throws IOException     {                throw new UnsupportedOperationException("Unable to create directory");     }      @Override     public File[] getRoots()     {         return rootDirectories;     }      @Override     public boolean isRoot(File file)     {         for (File root : rootDirectories) {             if (root.equals(file)) {                 return true;             }         }         return false;     } } 

You'll obviously need to make a better "createNewFolder" method, but this does restrict the user to one of more directories.

And use it like this:

FileSystemView fsv = new DirectoryRestrictedFileSystemView(new File("X:\\")); JFileChooser fileChooser = new JFileChooser(fsv); 

or like this:

FileSystemView fsv = new DirectoryRestrictedFileSystemView( new File[] {     new File("X:\\"),     new File("Y:\\") }); JFileChooser fileChooser = new JFileChooser(fsv); 
like image 131
Allain Lalonde Avatar answered Sep 23 '22 17:09

Allain Lalonde


You can probably do this by setting your own FileSystemView.

like image 21
McDowell Avatar answered Sep 20 '22 17:09

McDowell