FileChooser Filter





8
Date Submitted Tue. Feb. 14th, 2006 2:59 PM
Revision 1 of 1
Coder mattrmiller
Tags File | Filter | Java | JFileChooser
Comments 0 comments
Set's a filter for what files to accept when using JFileChooser.


// Create file chooser
        final JFileChooser fChooser = new JFileChooser(new File("MyFile.txt"));
        fChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
       
        // Show
        fChooser.setFileFilter(new ChooserFilter("txt"));
        nRet = fChooser.showSaveDialog(this);
        if (nRet == JFileChooser.APPROVE_OPTION)
        {
                // DO Something
        }

 


// Imports
import java.io.*;
import javax.swing.filechooser.FileFilter;

public class ChooserFilter
        extends FileFilter
{
        // Declare variables
        // -- Private
        private String m_strExtention = null;

        public ChooserFilter(String strExt)
        {
                m_strExtention = strExt;
        }

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

                String s = f.getName();
                int i = s.lastIndexOf('.');

                if (i > 0 && i < s.length() - 1)
                {
                        String extension = s.substring(i + 1).toLowerCase();
                        if (m_strExtention.equals(extension))
                        {
                                return true;
                        }
                        else
                        {
                                return false;
                        }
                }

                return false;

        }

        public String getDescription()
        {
                return "";
        }
}
 

Matthew R. Miller

www.bluecreststudios.com
=================
Matthew R. Miller

http://bluecreststudios.com
http://www.codeandcoffee.com

Comments

There are currently no comments for this snippet.

Voting