FileFilter Class
Package: javax.swing
This abstract class lets you create a class that can filter the files displayed by the JFileChooser
class. For example, you can use this class to create a filter that will display only files with a certain filename extension in the file chooser. (For more information about file choosers and the JFileChooser
class, see JFileChooser Class.)
class JavaFilter
extends javax.swing.filechooser.FileFilter
Methods
Method |
Description |
|
You must implement this method to return |
|
You must implement this method to return the description string that is displayed in the Files of Type drop-down list in the chooser dialog box. |
The getDescription
method simply returns the text displayed in the Files of Type drop-down list. You usually implement it with a single return
statement that returns the description. Here’s an example:
public String getDescription()
{
return “Java files (*.java)”;
}
Here, the string Java files (*.java)
is displayed in the Files of Type drop-down list.
The accept
method does the work of a file filter. The file chooser calls this method for every file it displays. The file is passed as a parameter. The accept
method must return a Boolean that indicates whether the file is displayed.
The accept
method can use any criteria it wants to decide which files to accept and which files to reject. Most filters do this based on the file extension part of the filename.
Here’s a FileFilter
class that displays files with the extension .java
:
private class javaFilter
extends javax.swing.filechooser.FileFilter
{
public boolean accept(File f)
{
if (f.isDirectory())
return true;
String name = f.getName();
if (name.matches(“.*\.java”))
return true;
else
return false;
}
public String getDescription()
{
return “Java files (*.java)”;
}
}
After you create a class that implements a file filter, you can add the file filter to the JFileChooser
by calling the addChoosableFileFilter
method, passing a new instance of the FileFilter
class, like this:
fc.setChoosableFileFilter(new JavaFilter());
fc.setAcceptAllFileFilterUsed(false);
Then only file filters that you add to the file chooser appear in the Files of Type drop-down list.