我正在尝试为我的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我该如何解决这个问题?
发布于 2011-02-03 08:18:03
您需要添加至少一个扩展名作为第二个参数。在API中:
FileNameExtensionFilter(String description, String... extensions)
Parameters:
description - textual description for the filter, may be null
extensions - the accepted file name extensions发布于 2015-10-29 23:58:35
此外,如果你想要一个特定的文件扩展名并浏览文件夹,你可以尝试这样做:
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);https://stackoverflow.com/questions/4881442
复制相似问题