In this post, I will guide you how to add file filter for JFileChooser component in Java Swing applications.

You know, it’s very common to have a file extension filter for open/save dialog like the following screenshot:

file extension filter


In Swing, we can do that by using method
addChoosableFileFilter(FileFilter filter) of the class JFileChooser.
Create a class that extends
FileFilter abstract class and overrides its two methods:
    • boolean accept(File f): returns true if the file f satisfies a filter condition. The condition here is the extension of the file.
    • String getDescription(): returns a description which is displayed in the dialog’s Files of type section.

The following code shows an example of adding a filter for files of type PDF:

JFileChooser fileChooser = new JFileChooser();
fileChooser.addChoosableFileFilter(new FileFilter() { public String getDescription() { return "PDF Documents (*.pdf)"; } public boolean accept(File f) { if (f.isDirectory()) { return true; } else { return f.getName().toLowerCase().endsWith(".pdf"); } } });

However, what if we need to add several filters, such as for .docx, .xlsx files? Well, one solution is repeating the above code for each file type – but that is not good in terms of code reusability. So, it’s better to create a separate, generalized class for extending the FileFilter abstract class, and parameterize the file extension and description, as shown in the following code:

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

public class FileTypeFilter extends FileFilter {
    private String extension;
    private String description;

    public FileTypeFilter(String extension, String description) {
        this.extension = extension;
        this.description = description;
    }

    public boolean accept(File file) {
        if (file.isDirectory()) {
            return true;
        }
        return file.getName().endsWith(extension);
    }

    public String getDescription() {
        return description + String.format(" (*%s)", extension);
    }
}

Then we can add several file filters as following:

FileFilter docFilter = new FileTypeFilter(".docx", "Microsoft Word Documents");
FileFilter pdfFilter = new FileTypeFilter(".pdf", "PDF Documents");
FileFilter xlsFilter = new FileTypeFilter(".xlsx", "Microsoft Excel Documents");
fileChooser.addChoosableFileFilter(docFilter);
fileChooser.addChoosableFileFilter(pdfFilter);
fileChooser.addChoosableFileFilter(xlsFilter);

Before Java 6, we have to write the above code manually. Fortunately, since Java 6, Swing adds a new class called FileNameExtensionFilter, which makes adding file filters easier. For example:

fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("PDF Documents", "pdf"));

We also can accumulate multiple extensions together:

fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Images", "jpg", "png", "gif", "bmp"));

 And following is a sample program that shows an open dialog when the button Browse is clicked, with some filters for: PDF documents, MS Office documents, and Images.

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 * Demo of file extension filter. Applied since Java 1.6
 * @author www.codejava.net
 *
 */
public class FileExtensionFilterDemo extends JFrame {
    private JButton buttonBrowse;

    public FileExtensionFilterDemo() {
        super("Demo File Type Filter");
        setLayout(new FlowLayout());
        buttonBrowse = new JButton("Browse...");

        buttonBrowse.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                showOpenFileDialog();
            }
        });

        getContentPane().add(buttonBrowse);
        setSize(300, 100);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) { }

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new FileExtensionFilterDemo();
            }
        });
    }

    private void showOpenFileDialog() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

        fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("PDF Documents", "pdf"));
        fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("MS Office Documents", "docx", "xlsx", "pptx"));
        fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Images", "jpg", "png", "gif", "bmp"));

        fileChooser.setAcceptAllFileFilterUsed(true);

        int result = fileChooser.showOpenDialog(this);

        if (result == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();
            System.out.println("Selected file: " + selectedFile.getAbsolutePath());
        }
    }
}

 

Related Swing File Chooser Tutorials:

 

Other Java Swing Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Attachments:
Download this file (FileExtensionFilterDemo.java)FileExtensionFilterDemo.java[A sample Swing application that demonstrates using FileNameExtensionFilter]2 kB
Download this file (FileTypeFilter.java)FileTypeFilter.java[File extension filter class (before Java 6)]0.5 kB

Add comment

   


Comments 

#12Rizvi Shanas2021-09-24 22:03
This code is useful for me, thank you, may God bless you with your time and effort.
Quote
#11hm2019-12-03 03:38
Quoting Linke:
That's great! But what if we want to hide the "[All files]" option?

u do:
fileChooser.setAcceptAllFileFilterUsed(false);
Quote
#10yahia2019-11-19 13:02
thanks for this valuable information ,thanks once again
Quote
#9compao2019-09-27 09:58
Very clearly explaned. Thanks a lot.
Quote
#8Walter Williams2019-07-08 21:24
Just to let you know. In the first code snippet there is an html tag "", a line break.
Quote