WebNFS Developer's Guide

Filtering Files

As mentioned in "Customizing the File Chooser", three different file filters can be applied to a file chooser. In this program, a filter chosen by the user is enabled. If the Add JPEG and GIF Filters radio button is selected, the resulting file chooser presents the user with several filters to choose from, as shown in Figure 5-8:

Figure 5-8 Filtering Files

Graphic

The file filters used by XFileChooserDemo are described in the class ExampleFileFilter, found in ExampleFileFilter.java (shown in "ExampleFileFilter"). ExampleFileFilter takes two arguments: a file extension (for example, .jpg) and a description of the file, and filters files appropriately.

Here is where XFileChooserDemo instantiates the various filters:


jpegFilter = new ExampleFileFilter("jpg", "JPEG
Compressed Image Files");
gifFilter = new ExampleFileFilter("gif", "GIF
Image Files");
bothFilter = new ExampleFileFilter(new String[] ""jpg", "gif"}, "JPEG
and GIF Image Files");

The program's OptionListener() checks to see if the radio buttons governing filters have been changed. If the user has selected the Add JPEG and GIFs button, OptionListener() adds the various filters provided by ExampleFileFilter, using the addChoosableFileFilter() method inherited from JFileChooser:


class OptionListener implements ActionListener {
   public void actionPerformed(ActionEvent e) {
      JComponent c = (JComponent) (e.getsource();
...
        else if (c == addFiltersButton) {
           chooser.addChoosableFileFilter(bothFilter);
              chooser.addChoosableFileFilter(jpgFilter);
           chooser.addChoosableFileFilter(gifFilter);
        }

(The program could have used finer control in determining which filters to add to the file chooser, but the approach used here minimizes the number of radio buttons cluttering the main window.)

When the user chooses a new filter in the file chooser, a CHOOSABLE_FILE_FILTER_CHANGED_PROPERTY is fired off, and the panel displaying the list of files gets updated accordingly, to show only the filtered files.