Java Reference
In-Depth Information
Working with File Filters
The JFileChooser supports three ways of filtering its file and directory list. The first two involve
working with the FileFilter class, and the last involves hidden files. First, let's look at the
FileFilter class.
FileFilter is an abstract class that works something like FilenameFilter in AWT. However,
instead of working with strings for directory and file names, it works with a File object. For
every File object that is to be displayed (both files and directories), the filter decides whether
the File can appear within the JFileChooser . In addition to providing an acceptance mecha-
nism, the filter also provides a description, or name, for when the description is displayed to a
user. These two capabilities are reflected in the following two methods of the class definition:
public abstract class FileFilter {
public FileFilter();
public abstract String getDescription();
public abstract boolean accept(File file);
}
Note Given the abstract nature of this class, it should be an interface, but it isn't.
To demonstrate a file filter, Listing 9-15 creates one that accepts an array of file extensions.
If the file sent to accept() is a directory, it's automatically accepted. Otherwise, the file exten-
sion must match one of the extensions in the array provided, and the character preceding the
extension must be a period. For this particular filter, the comparisons are case-insensitive.
Listing 9-15. A Custom FileFilter for Use with a JFileChooser
import javax.swing.filechooser.*;
import java.io.File; // avoid FileFilter name conflict
public class ExtensionFileFilter extends FileFilter {
String description;
String extensions[];
public ExtensionFileFilter(String description, String extension) {
this(description, new String[] { extension} );
}
 
Search WWH ::




Custom Search