Question

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"));
Was it helpful?

Solution

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());

}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top