0

I am attempting to make a program, and it involves a JFileChooser. I am trying to make it so that the users can only pick .zip files. My code is

JFileChooser finder = new JFileChooser();
finder.setFileFilter(new FileNameExtensionFilter(null, ".zip"));

This seems to me like it would run fine, however when I go to a folder with a .zip file, the .zip files are gray, and I can't choose them. How do I fix this? Also, as a side question, how do I get rid of the "All Files" option in the JFileChooser window?

user600842
  • 141
  • 1
  • 5
  • 13

3 Answers3

10

Yes just replace ".zip" with "zip" and also you can remove "All Files" option and make it as "Zip Files". Use following code for that...

JFileChooser fileChooser = new JFileChooser();
// select only zip files and add "Zip Files" option
fileChooser.setFileFilter(new FileNameExtensionFilter("Zip Files", "zip"));
// remove "All Files" option
fileChooser.removeChoosableFileFilter(fileChooser.getAcceptAllFileFilter());
Chathuranga Withana
  • 862
  • 1
  • 9
  • 12
  • I tried to use this code and it works fine, But in the field "Files of Type" I was expecting "*.txt" to appear, but it doesn't. How to show the user that what type of file is expected from them to choose? – MK Singh Oct 24 '13 at 12:26
5

Use "zip" as an extension filter, not ".zip".

Tugrul Ates
  • 9,451
  • 2
  • 33
  • 59
  • Also, how do I get the name of the file without the .zip extension? – user600842 Mar 11 '11 at 23:28
  • See http://stackoverflow.com/questions/924394/how-to-get-file-name-without-the-extension – Tugrul Ates Mar 11 '11 at 23:33
  • Thank you, but that thread talks about FilenameUtils which doesn't work with my version of Java/Eclipse. Eclipse just underlines it in red and there is no quickfix available. I have also tried importing the package that it comes from according to the thread, but that doesn't help. Any ideas? – user600842 Mar 12 '11 at 14:39
  • 1
    How about the regex answer there? – Tugrul Ates Mar 12 '11 at 17:20
1

The extension for the FileFilter should not contain the dot. The dot is the separator between the name and extention parts and not part of the extention. Try it with just zip not .zip. See the javadoc for FileFilter for more.

finder.setFileFilter(new FileNameExtensionFilter(null, "zip"));
krock
  • 28,904
  • 13
  • 79
  • 85