Setting a file filter in a JFileChooser dialog

Here’s an example that shows you how to restrict the files shown in the dialog. It will only show the .gif files. The idea is to create a FileFilter and implement the method accept that will be invoked for every file in the selected directory. You can specify any custom filtering in there.

import javax.swing.filechooser.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.File;
 
public class Main extends JFrame
{
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
 
   public Main() {
      JButton fileButton = new JButton("Select File");
      fileButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            File file = getFileFromUser(getGifFileFilter());
            if (file != null)
               System.out.println(file.getName());
         }
      });
      getContentPane().add(fileButton);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
 
      pack();
   }
   
   public FileFilter getGifFileFilter() {
      FileFilter ff = new FileFilter() {
         public boolean accept(File f) {
            if (f.isDirectory()) 
               return true;
            else if (f.getName().toLowerCase().endsWith(".gif"))
               return true;
            return false;
         }
 
         public String getDescription() {
            return "GIF image";
         }
      };
 
      return ff;
   }
   
   public File getFileFromUser(FileFilter ff) {
      JFileChooser fc = new JFileChooser();
 
      // use current directory
      fc.setCurrentDirectory(new File("c:\"));
 
      // set file filter if specified
      if (ff != null)
         fc.setFileFilter(ff);
 
      // show dialog for opening files
      int result = fc.showOpenDialog(this);
 
      if (result != fc.APPROVE_OPTION) 
         return null;
       
      return fc.getSelectedFile();
   }
}