0

I have a requirement where a user browse through JFileChooser and selects a folder.

But while doing this selection the user should not be allowed to select root drive. By "Root Drive" I mean C: or D: etc. in Windows and / in UNIX/Linux.

I think here I can not use filters for JFileChooser as its job is to browse through the files and hence it does not make any sense to filter the drive itself.

Please suggest a proper solution which may work on all Windows/Linux file System.

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
Abhinav
  • 1,720
  • 4
  • 21
  • 33

2 Answers2

0

You can attach event with it and then in your event code apply filters to meet your requirement.

Muhammad Imran Tariq
  • 22,654
  • 47
  • 125
  • 190
0

How about this?

//This file filter shouldn't be added to the chooser
final FileFilter filter = new FileFilter() {
    @Override
    public boolean accept(File f) {
        if(!f.isDirectory())
            return false;
        for(File root : File.listRoots())
            if(f.equals(root))
                return false;
        return true;
    }
    @Override
    public String getDescription() { return null; }
};
JFileChooser chooser = new JFileChooser() {
    @Override
    public void approveSelection() {
        if(filter.accept(getSelectedFile()))
            super.approveSelection();
        else
            JOptionPane.showMessageDialog(this, "Illegal selection");
    }
};
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
Lone nebula
  • 4,768
  • 2
  • 16
  • 16