FileFilter for JFileChooser

62.8k views Asked by At

I want to restrict a JFileChooser to select only mp3 files. But, the following code allows all file types:

FileFilter filter = new FileNameExtensionFilter("MP3 File","mp3");
fileChooser.addChoosableFileFilter(filter);
fileChooser.showOpenDialog(frame);
File file = fileChooser.getSelectedFile();
5

There are 5 answers

0
Paul Samsotha On BEST ANSWER

Try and use fileChooser.setFileFilter(filter) instead of fileChooser.addChoosableFileFilter(filter);

0
Amir Afghani On

Try:

FileFilter filter = new FileNameExtensionFilter("My mp3 description", "mp3");

The first argument is simply a description of the FileNameExtensionFilter - and since the second argument is var args, you can leave it out like you did, effectively meaning there is no filter.

1
Anis H On

This code snippet may help you:

JFileChooser jfc=new JFileChooser(System.getProperty("user.dir","."));

FileFilter ff = new FileFilter(){
    public boolean accept(File f){
        if(f.isDirectory()) return true;
        else if(f.getName().endsWith(".mp3")) return true;
            else return false;
    }
    public String getDescription(){
        return "MP3 files";
    }
};

jfc.removeChoosableFileFilter(jfc.getAcceptAllFileFilter());
jfc.setFileFilter(ff);

if(jfc.showDialog(frame,"openG")==JFileChooser.APPROVE_OPTION){
        String fileName = jfc.getSelectedFile().getPath();
}
1
Samuel On

If you want only mp3 files:

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;

public class SalutonFrame {

    public static void main(String[] args) {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setAcceptAllFileFilterUsed(false);
        FileNameExtensionFilter filter = new FileNameExtensionFilter("MPEG3 songs", "mp3");
        fileChooser.addChoosableFileFilter(filter);
        fileChooser.showOpenDialog(null);

    }
}
1
Sage On

fileChooser.addChoosableFileFilter(filter) will add a custom file filter to the list of user-choosable filters. By default, the list of user-choosable filters includes the Accept All filter, which enables the user to see all non-hidden files.

You will need to invoke: fileFilter.setAcceptAllFileFilterUsed(false)

The setAcceptAllFileFilterUsed(boolean) determines whether the AcceptAll FileFilter is used as an available choice in the choosable filter list. If false, the AcceptAll file filter is removed from the list of available file filters. If true, the AcceptAll file filter will become the the actively used file filter.