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();
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.
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.
Try and use fileChooser.setFileFilter(filter)
instead of fileChooser.addChoosableFileFilter(filter);
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With