代码改变世界

JFileChooser添加文件过滤

2013-11-26 01:10  _cha1R  阅读(3484)  评论(0编辑  收藏  举报

这是java的Swing里的一个选择文件的控件,我们要如何使用它?首先来看看JDKAPI的说明:

public class JFileChooserextends JComponentimplements Accessible

JFileChooser 为用户选择文件提供了一种简单的机制。有关使用 JFileChooser 的更多信息,请参阅 《The Java Tutorial》 中的 How to Use File Choosers 一节。

以下代码弹出一个针对用户主目录的文件选择器,其中只显示 .jpg 和 .gif 图像: 

    JFileChooser chooser = new JFileChooser();
// Note: source for ExampleFileFilter can be found in FileChooserDemo,
    // under the demo/jfc directory in the JDK.
    ExampleFileFilter filter = new ExampleFileFilter();
    filter.addExtension("jpg");
    filter.addExtension("gif");
    filter.setDescription("JPG & GIF Images");
    chooser.setFileFilter(filter);
    int returnVal = chooser.showOpenDialog(parent);
    if(returnVal == JFileChooser.APPROVE_OPTION) {
       System.out.println("You chose to open this file: " +
            chooser.getSelectedFile().getName());
    }

这是一个例子,上面代码中,new了一个ExampleFileFilter,然后设置它允许的文件后缀名,再设置描述。最后JFileChooser设置一个文件过滤器就OK了。使用的使用showOpenDialog()。

但是这个ExampleFileFilter是怎么来的呢?我们注意到上面有两行注释:

// Note: source for ExampleFileFilter can be found in FileChooserDemo,
// under the demo/jfc directory in the JDK.

它的意思大概是这个ExampleFileFilter类的源码,在FileChooserDemo的jfc文件夹里可以找到。

然后我去找了一下,发现没有这个类源码。

我看下chooser.setFileFilter(xxx)接受的类型,是个抽象类:

/*
 * %W% %E%
 *
 * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package javax.swing.filechooser;

import java.io.File;

/**
 * <code>FileFilter</code> is an abstract class used by {@code JFileChooser}
 * for filtering the set of files shown to the user. See 
 * {@code FileNameExtensionFilter} for an implementation that filters using
 * the file name extension.
 * <p>
 * A <code>FileFilter</code> 
 * can be set on a <code>JFileChooser</code> to
 * keep unwanted files from appearing in the directory listing.
 * For an example implementation of a simple file filter, see
 * <code><i>yourJDK</i>/demo/jfc/FileChooserDemo/ExampleFileFilter.java</code>.
 * For more information and examples see 
 * <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/filechooser.html">How to Use File Choosers</a>,
 * a section in <em>The Java Tutorial</em>.
 *
 * @see FileNameExtensionFilter
 * @see javax.swing.JFileChooser#setFileFilter
 * @see javax.swing.JFileChooser#addChoosableFileFilter
 *
 * @version %I% %G%
 * @author Jeff Dinkins
 */
public abstract class FileFilter {
    /**
     * Whether the given file is accepted by this filter.
     */
    public abstract boolean accept(File f);

    /**
     * The description of this filter. For example: "JPG and GIF Images"
     * @see FileView#getName
     */
    public abstract String getDescription();
}

从类的注释可以看到,我们简单地继承它,实现这两个方法就可以实现文件过滤。简单说明:

accept(File f) 方法:对文件进行过滤,通过就返回true。我们可以简单地判断文件的后缀名

getDescription()方法:文件类型的描述,直接返回String方可。

我们可以简单实现它:

public class MyFileFilter extends FileFilter {
        public boolean accept(File f) {
            if(f.getName().contains(".jpg") || f.isDirectory()){
                return true;
            }
return false; } public String getDescription() { return "jpg文件"; } }

然后在fileChooser.setFileFilter(MyFileFilter) 即可,效果如下:

这样一个简单的文件过滤就实现了。

======================================================================

最后我还是不死心,终于在jdk1.4的demo里找到了ExampleFileFilter.java。不知道为什么JDK1.5移除了它。附上:

import java.io.File;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.swing.filechooser.FileFilter;

public class MyFileFilter extends FileFilter {
    private static String TYPE_UNKNOWN = "Type Unknown";
    private static String HIDDEN_FILE = "Hidden File";
    private Hashtable filters = null;
    private String description = null;
    private String fullDescription = null;
    private boolean useExtensionsInDescription = true;

    public MyFileFilter() {
        this.filters = new Hashtable();
    }

    public MyFileFilter(String extension) {
        this(extension, null);
    }

    public MyFileFilter(String extension, String description) {
        this();
        if (extension != null)
            addExtension(extension);
        if (description != null)
            setDescription(description);
    }

    public MyFileFilter(String[] filters) {
        this(filters, null);
    }

    public MyFileFilter(String[] filters, String description) {
        this();
        for (int i = 0; i < filters.length; i++) {
            // add filters one by one
            addExtension(filters[i]);
        }
        if (description != null)
            setDescription(description);
    }

    public boolean accept(File f) {
        if (f != null) {
            if (f.isDirectory()) {
                return true;
            }
            String extension = getExtension(f);
            if (extension != null && filters.get(getExtension(f)) != null) {
                return true;
            }
            ;
        }
        return false;
    }

    public String getExtension(File f) {
        if (f != null) {
            String filename = f.getName();
            int i = filename.lastIndexOf('.');
            if (i > 0 && i < filename.length() - 1) {
                return filename.substring(i + 1).toLowerCase();
            }
            ;
        }
        return null;
    }

    public void addExtension(String extension) {
        if (filters == null) {
            filters = new Hashtable(5);
        }
        filters.put(extension.toLowerCase(), this);
        fullDescription = null;
    }

    public String getDescription() {
        if (fullDescription == null) {
            if (description == null || isExtensionListInDescription()) {
                fullDescription = description == null ? "(" : description
                        + " (";
                // build the description from the extension list
                Enumeration extensions = filters.keys();
                if (extensions != null) {
                    fullDescription += "." + (String) extensions.nextElement();
                    while (extensions.hasMoreElements()) {
                        fullDescription += ", ."
                                + (String) extensions.nextElement();
                    }
                }
                fullDescription += ")";
            } else {
                fullDescription = description;
            }
        }
        return fullDescription;
    }

    public void setDescription(String description) {
        this.description = description;
        fullDescription = null;
    }

    public void setExtensionListInDescription(boolean b) {
        useExtensionsInDescription = b;
        fullDescription = null;
    }

    public boolean isExtensionListInDescription() {
        return useExtensionsInDescription;
    }

}

大家直接用它就可以了。

这个网站很多学习资料