Below is my code to open a JFileChooser
on the click of a button. I have created a filter to allow the selection of only .jpg files, but my code doesn't work as expected. All types of files are shown in JFileChooser
diaog box. Part of code:
MyFileFilter filter;
fPhoto=new JFileChooser();
fPhoto.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fPhoto.setFileFilter(filter);
MyFileFilter class:
public class MyFileFilter extends javax.swing.filechooser.FileFilter{
public boolean accept(File f){
return f.isDirectory()||(f.isFile()&&f.getName().toLowerCase().endsWith(".jpg"));
}
public String getDescription(){
return ".jpg files";
}
}
You need to instantiate your filter
. Having a null
FileFilter
will result in no file types being filtered out:
MyFileFilter filter = new MyFileFilter();