Search code examples
javaswingjfilechooserfilefilter

File Filter does not appear on JFileChooser in Java swing


I have a JButton that needs to open a file of a specific extension. In brief, I define a JButton add an actionlistener to it that fires a JFileChooser, if JButton is clicked. I want to add a file filter so that only files of extension .mpg will be shown on the JFileChooser.

The compilation shows no errors, but on the swing the JFileChooser shows no filtering of the available files (nor the option 'Movie files' in the combobox appears - just 'All files'). In two words, it seems that addChoosableFileFilter has no effect whatsoever.

My code is:

final JFileChooser jfc = new JFileChooser(moviedir);
//add File Filter
jfc.addChoosableFileFilter(new FileFilter() {
@Override
public String getDescription() {
return "Movie files (*.mpg)";
}
@Override
public boolean accept(File f) {
if (f.isDirectory()) {return true;} 
else {return f.getName().toLowerCase().endsWith(".mpg");}
 }
});

I have also tried the alternative of

jfc.addChoosableFileFilter(new FileNameExtensionFilter("Movie files", "mpg"));

with the same fate. All the above are on JPanel of a JFrame of my swing.

I 've read many related threads but no luck.

Thanks in advance for comments.


Solution

  • JFileChooser provides a simple mechanism for the user to choose a file. For information about using JFileChooser, see How to Use File Choosers, a section in The Java Tutorial.

    The following code pops up a file chooser for the user's home directory that sees only .jpg and .gif images:

    JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter(
        "JPG & GIF Images", "jpg", "gif");
    chooser.setFileFilter(filter);
    int returnVal = chooser.showOpenDialog(parent);
    if(returnVal == JFileChooser.APPROVE_OPTION) {
       System.out.println("You chose to open this file: " +
            chooser.getSelectedFile().getName());
    }
    

    Try this. Copied from here