dev
dev

Reputation: 2584

FileFilter for JFileChooser

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

Upvotes: 22

Views: 64384

Answers (5)

Samuel
Samuel

Reputation: 2156

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

    }
}

Upvotes: 21

Sage
Sage

Reputation: 15408

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.

Upvotes: 4

Paul Samsotha
Paul Samsotha

Reputation: 208964

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

Upvotes: 31

Anis H
Anis H

Reputation: 1150

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

Upvotes: 4

Amir Afghani
Amir Afghani

Reputation: 38521

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.

Upvotes: 9

Related Questions