Adding a Filter to a File Chooser Dialog

This example add a filter for .java files to the file chooser.
JFileChooser fileChooser = new JFileChooser(new File(filename)); fileChooser.addChoosableFileFilter(new MyFilter()); // Open file dialog. fileChooser.showOpenDialog(frame); openFile(fileChooser.getSelectedFile()); class MyFilter extends javax.swing.filechooser.FileFilter { public boolean accept(File file) { String filename = file.getName(); return filename.endsWith(".java"); } public String getDescription() { return "*.java"; } }

Comments

8 Mar 2010 - 7:10am by Ondrej Bartonek (not verified)

Now you cannot browse directories, you are missing directory handling. To get it work correctly just add the following if clause into accept method:

if (file.isDirectory()) { return true; }

10 Mar 2010 - 10:51pm by one (not verified)

Thanks

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.