0

I am trying to set the file filter for my JFileChooser. This is my code:

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

When I run my program, the file chooser comes up, but it won't let me pick any .txt files. Instead, it says this in the console:

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

How do i fix this?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
user600842
  • 141
  • 1
  • 5
  • 13

2 Answers2

1

You need to add at least one extension as a second paramter. From the API:

FileNameExtensionFilter(String description, String... extensions) 

Parameters:
description - textual description for the filter, may be null
extensions - the accepted file name extensions
jzd
  • 23,473
  • 9
  • 54
  • 76
0

Also if you want an specific files extensions and navigate thru folders you can try this:

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);
Luis Herrería
  • 101
  • 1
  • 6