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";
}
}
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; }
Thanks