简体   繁体   中英

java jfilechooser to list only “hello*.txt files” and no directory changing

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

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

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM