Question

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();
Was it helpful?

Solution

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

OTHER TIPS

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);

    }
}

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.

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.

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();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top