2

I am trying to use JFileChooser to select files with this name format: LS48*.drv. at the same time I want to limit the user to look into only a specific directory say c:\data. So I don't want the user to be able to change directories or to other drive names. Base of my code segment below can you please provide me some hints:

 m_fileChooser = new JFileChooser("c:\\data"); // looking for LS48*.drv files
  m_fileChooser.setFileFilter(new FileNameExtensionFilter("drivers(*.drv, *.DRV)", "drv", "DRV"));
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
C graphics
  • 7,308
  • 19
  • 83
  • 134
  • I got this tip from @Boro to use this code for restricting user to look into specific directory only: http://tips4java.wordpress.com/2009/01/28/single-root-file-chooser/ – C graphics Jun 15 '12 at 00:01

2 Answers2

6

You will need to implement a FileFilter subclass of your own, and set this to the file chooser instead of a FileNameExtensionFilter instance.

And your accept method in this subclass will be something like the following:

private static final Pattern LSDRV_PATTERN = Pattern.compile("LS48.*\\.drv");
public boolean accept(File f) {
    if (f.isDirectory()) {
        return false;
    }

    return LSDRV_PATTERN.matcher().matches(f.getName());

}
Christopher Schultz
  • 20,221
  • 9
  • 60
  • 77
Hakan Serce
  • 11,198
  • 3
  • 29
  • 48
  • Thanks for your answer. Can you check out this question please? http://stackoverflow.com/questions/11041575/using-all-jcombobox-jtextfield-jfilechooser-as-table-editor-overrides-the-re – C graphics Jun 14 '12 at 23:48
4

To prevent directory changes use this:

File root = new File("c:\\data");
FileSystemView fsv = new SingleRootFileSystemView( root );
JFileChooser chooser = new JFileChooser(fsv);

Check this: http://tips4java.wordpress.com/2009/01/28/single-root-file-chooser/

As for the file name pattern, you could use java regular expressions.

wederchr
  • 494
  • 4
  • 5
  • 1
    Is this the class you are referring to http://tips4java.wordpress.com/2009/01/28/single-root-file-chooser/ If so please edit it into your code. – Boro May 26 '12 at 00:51
  • Thanks I just added via a coment. Also I was wondering if you can check out this question: http://stackoverflow.com/questions/11041575/using-all-jcombobox-jtextfield-jfilechooser-as-table-editor-overrides-the-re – C graphics Jun 15 '12 at 00:03