How to Add File Filter for JFileChooser dialog
- Details
- Written by Nam Ha Minh
- Last Updated on 04 July 2019   |   Print Email
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:
In Swing, we can do that by using methodaddChoosableFileFilter(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:
- File picker component in Swing
- Show save file dialog using JFileChooser
- Show simple open file dialog using JFileChooser
Other Java Swing Tutorials:
- Java Swing Hello World Tutorial for Beginners Using Text Editor
- JFrame basic tutorial and examples
- JPanel basic tutorial and examples
- JLabel basic tutorial and examples
- JTextField basic tutorial and examples
- JButton basic tutorial and examples
Comments
u do:
fileChooser.setAcceptAllFileFilterUsed(false);