FileDocCategorySizeDatePackage
ExtensionFilter.javaAPI DocExample1547Sun Mar 28 07:24:06 BST 1999com.macfaq.swing.filechooser

ExtensionFilter.java

package com.macfaq.swing.filechooser;

import java.io.*;
import com.sun.java.swing.filechooser.*;
import com.sun.java.swing.*;


public class ExtensionFilter extends com.sun.java.swing.filechooser.FileFilter {

  String extension;
  String description;

  public ExtensionFilter(String extension, String description) {

    if (extension.indexOf('.') == -1) {
      extension = "." + extension;
    }
    this.extension = extension;
    this.description = description;
    
  }
  
  public boolean accept(File f) {
  
    if (f.getName().endsWith(extension)) {
      return true;
    }
    else if (f.isDirectory()) { 
      return true;
    }
    return false;

  }
    
  public String getDescription() {
    return this.description + "(*" + extension + ")";
  }
  
  // test
  public static void main(String[] args) {
  
 
    JFrame parent = new JFrame(); // never shown
    JFileChooser fc = new JFileChooser();
    fc.setDialogTitle("Please choose a file: ");
    fc.addChoosableFileFilter(new ExtensionFilter("txt", "Text Files"));
    fc.addChoosableFileFilter(new ExtensionFilter("java", "Java Source Code"));
    fc.addChoosableFileFilter(new ExtensionFilter(".c", "C Source Code"));
    fc.addChoosableFileFilter(new ExtensionFilter(".pl", "Perl Source Code"));
    fc.addChoosableFileFilter(new ExtensionFilter(".html", "HTML Files"));
 
    fc.showOpenDialog(parent);
    parent.dispose();
     
    // Work around annoying AWT non-daemon thread bug
    System.exit(0);
  }

}