Return to Snippet

Revision: 20886
at November 29, 2009 22:22 by Macianer


Initial Code
import javax.swing.filechooser.FileFilter;
import java.io.File;

public class Filter extends FileFilter {
    private boolean acceptDirs = true;
    private String  desc;
    private String  ext;

    public Filter(String ext) {
        this.ext  = ext;
        this.desc = ext + "-Files (" + generateExtensionString(ext) + ")";
    }

    public Filter(String ext, String desc) {
        this.ext  = ext;
        this.desc = desc + " (" + generateExtensionString(ext) + ")";
    }

    public String getDescription() {
        return desc;
    }

    public boolean accept(File f) {
        if (f.isDirectory() && acceptDirs) {
            return true;
        }

        if (!isMultiExtensionString(ext)) {
            return f.getName().endsWith(ext);
        }

        String[] exts = ext.split(",");

        for (int i = 0; i < exts.length; i++) {
            if (f.getName().endsWith(exts[i])) {
                return true;
            }
        }

        return false;
    }                

    protected boolean isMultiExtensionString(String ext) {
        return ext.indexOf(',') >= 0;
    }

    protected String generateExtensionString(String ext) {
        String[]     exts = ext.split(",");
        StringBuffer sb   = new StringBuffer();

        for (int i = 0; i < exts.length; i++) {
            sb.append("*.");
            sb.append(exts[i]);

            if (i != exts.length - 1) {
                sb.append(",");
            }
        }

        return sb.toString();
    }
}

Initial URL

                                

Initial Description

                                

Initial Title
Filter for JFileChooser

Initial Tags

                                

Initial Language
Java