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
  • 63,838
  • 26
  • 184
  • 242
Abhinav
  • 1,678
  • 3
  • 21
  • 31

2 Answers2

0

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

Muhammad Imran Tariq
  • 21,578
  • 43
  • 119
  • 188
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,528
  • 2
  • 15
  • 16