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.)

tip.eps For some reason, the Java designers gave this class the same name as an interface that’s in the java.io package, which is also frequently used in applications that work with files. As a result, you need to fully qualify this class when you extend it, like this:

class JavaFilter

extends javax.swing.filechooser.FileFilter

Methods

Method

Description

public boolean abstract accept(File f)

You must implement this method to return true if you want the file to be displayed in the chooser or false if you don’t want the file to be displayed.

public String abstract getDescription()

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

tip.eps If you want, you can remove the All Files filter by calling the method setAcceptAllFileFilterUsed, like this:

fc.setAcceptAllFileFilterUsed(false);

Then only file filters that you add to the file chooser appear in the Files of Type drop-down list.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset