Create a FileFilter using Java

Post date: Mar 29, 2011 5:12:42 AM

Create a FileFilter Class:

 import java.io.File;

import javax.swing.filechooser.FileFilter;

public class IconImageFilter extends FileFilter {

          //Accept all directories and all gif, jpg, tiff, or png files.

          public boolean accept(File f) {

              if (f.isDirectory()) {

                  return true;

              }

              String extension = Utils.getExtension(f);

              if (extension != null) {

                  if (extension.equals(Utils.tiff) ||

                      extension.equals(Utils.tif) ||

                      extension.equals(Utils.gif) ||

                      extension.equals(Utils.jpeg) ||

                      extension.equals(Utils.jpg) ||

                      extension.equals(Utils.png)) {

                          return true;

                  } else {

                      return false;

                  }

              }

              return false;

          }

           //The description of this filter

          public String getDescription() {

              return "Icon Images";

          }

      }

Once you create this class, then you need to add it into the JFileChooser by using following code

JFileChooser fileChooser = new JFileChooser();

            fileChooser.setFileFilter(new IconImageFilter());

            //Disable to choosing the All the file option

            fileChooser.setAcceptAllFileFilterUsed(false);    

            int returnValue=0;

            //For select the project file

            int selectValue=JFileChooser.APPROVE_OPTION;

           while(selectValue== JFileChooser.APPROVE_OPTION){

               returnValue = fileChooser.showOpenDialog(this);

                //Return 1 if file is selected

                  if(returnValue == JFileChooser.APPROVE_OPTION){

                        //Get the selected file                  

                        selectedFile = fileChooser.getSelectedFile();

                              //Set the path into the text box

                         System.out.println(selectedFile.getPath());                                    break;           

                        }                       

                        else{

                              //Selected wrong file

                                                         selectValue=JOptionPane.showConfirmDialog(this, "Please Select JAR, WAR,JAVA or ZIP files!","Oops Wrong File!",JOptionPane.OK_OPTION,JOptionPane.ERROR_MESSAGE);                     

                        }

                       

                  }