FileFilter for JFileChooser

拥有回忆 提交于 2019-11-28 07:08:02

问题


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

回答1:


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




回答2:


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

    }
}



回答3:


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.




回答4:


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.




回答5:


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


来源:https://stackoverflow.com/questions/20411919/filefilter-for-jfilechooser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!