How to use FileFilter in JFileChooser?

Filter files in JFileChooser
The javax.swing.filechooser.FileFilter class is used to set custom file type option in JFileChooser. You might already have noticed the setFileFilter() and addChoosableFileFilter() methods in the JFileChooser class. Now, let us see how to do this. Let us talk a bit about this class before we do the program.
A FileFilter is used to describe what files a user can select.
The FileFilter class is an abstract class containing two abstract methods

public String getDescription(): This is the description of the file type which will appear in the JFileChooser.
public boolean accept(File f): A File object is given, true/false must be returned. true will show the file and false will hide.
In this example, we are going to filter the popular image file types.

import javax.swing.*;
import java.awt.*;
import javax.swing.filechooser.*;
import java.io.File;
class FileFilterExample extends JFrame
{
JFileChooser jf;

public FileFilterExample()
{
createAndShowGUI();
}

private void createAndShowGUI()
{
setTitle("Filter files..");
setDefaultCloseOperation(EXIT_ON_CLOSE);

// Create JFileChooser
jf=new JFileChooser();

// Set the file filter
// This method sets the current file filter so
// that the JFileChooser comes with this filter

// Note that this method only adds a file filter
// and then sets it to the default
jf.setFileFilter(new FileFilter(){
public String getDescription()
{
return "Image Files Only";
}

public boolean accept(File f)
{
// You should accept the directories
if(f.isDirectory()) return true;

// Get the name of the file
String name=f.getName();

// Return true if the name ends with an image extension
return name.endsWith(".jpg") || name.endsWith(".jpeg") || name.endsWith(".gif") || name.endsWith(".png");
}
});

// This method shows or hides the "All Files" filter
// Default value is true i.e. "All Files" filter is allowed
jf.setAcceptAllFileFilterUsed(false);

// Show the open dialog
jf.showOpenDialog(this);

setSize(400,400);
setVisible(true);
}

public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable(){
public void run()
{
new FileFilterExample();
}
});
}
}

Make sure that you set the file filters before you show the open dialog or save dialog. Because, once the JFileChooser appears, you cannot set the file filter. If you like this post, share it. You might also like to know, how to delete a file through JFileChooser and get focus for JTextField in JFileChooser in NimbusLookAndFeel

No comments: