Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 268
dev Avatar asked Dec 05 '13 22:12

dev


People also ask

What is the purpose of JFileChooser?

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.

What is FileNameExtensionFilter in Java?

public final class FileNameExtensionFilter extends FileFilter. An implementation of FileFilter that filters using a specified set of extensions. The extension for a file is the portion of the file name after the last ".". Files whose name does not contain a "." have no file name extension.


2 Answers

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

like image 144
Paul Samsotha Avatar answered Sep 17 '22 15:09

Paul Samsotha


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

    }
}
like image 23
Samuel Avatar answered Sep 18 '22 15:09

Samuel