2011-02-03 28 views
0

我想爲我的JFileChooser設置文件過濾器。這是我的代碼:JFileChooser幫助

JFileChooser picker= new JFileChooser(); 
picker.setFileFilter(new FileNameExtensionFilter("txt")); 
int pickerResult = picker.showOpenDialog(getParent()); 
if (pickerResult == JFileChooser.APPROVE_OPTION){ 
System.out.println("This works!"); 
} 
if (pickerResult == JFileChooser.CANCEL_OPTION){ 
System.exit(1); 
} 

當我運行我的程序時,文件選擇器出現,但它不會讓我選擇任何.txt文件。相反,它在控制檯中表示:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Extensions must be non-null and not empty 

我該如何解決這個問題?

+0

可能重複http://stackoverflow.com/問題/ 5279358/JFileChooser的幫助) – 2014-04-15 14:36:12

回答

1

您需要添加至少一個擴展名作爲第二個參數。從API:

FileNameExtensionFilter(String description, String... extensions) 

Parameters: 
description - textual description for the filter, may be null 
extensions - the accepted file name extensions 
0

此外,如果你想要一個特定的文件擴展名和導航直通文件夾,你可以試試這個:

JFileChooser fc = new JFileChooser(path); 
fc.setFileSelectionMode(JFileChooser.FILES_ONLY); 
fc.addChoosableFileFilter(new FileFilter() { 

    @Override 
    public String getDescription() { 
     return "DAT Files"; 
    } 

    @Override 
    public boolean accept(File f) { 
     if (f.isDirectory()) 
      return true; 
     return f.getName().endsWith(".dat"); 
    } 

}); 
fc.setAcceptAllFileFilterUsed(false); 
[JFileChooser的幫助(的