FileFilter for JFileChooser

后端 未结 5 1503
走了就别回头了
走了就别回头了 2020-12-17 15:45

I want to restrict a JFileChooser to select only mp3 files. But, the following code allows all file types:

FileFilter filter = new FileNameExten         


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-17 16:07

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

提交回复
热议问题