Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter file types with JFileChooser

I am using JFileChooser to select a file and I am trying to limit the display to show only jpg or jpeg files. I have tried FileFilter and ChoosableFileFilter and it is not limiting the file selection. Here is my code:

JFileChooser chooser = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter("JPEG file", new String[] {"jpg", "jpeg"});
chooser.setFileFilter(filter);
chooser.addChoosableFileFilter(filter);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
  debug.put("You chose to open this file: " + chooser.getSelectedFile().getAbsolutePath());
  File selectedFile = new File(chooser.getSelectedFile().getAbsolutePath());
...
like image 312
Brian Avatar asked Oct 10 '13 17:10

Brian


2 Answers

Try this:

import javax.swing.JFileChooser;


JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileFilter() {

   public String getDescription() {
       return "JPG Images (*.jpg)";
   }

   public boolean accept(File f) {
       if (f.isDirectory()) {
           return true;
       } else {
           String filename = f.getName().toLowerCase();
           return filename.endsWith(".jpg") || filename.endsWith(".jpeg") ;
       }
   }
});
like image 139
Stefan Sprenger Avatar answered Oct 10 '22 11:10

Stefan Sprenger


Do you mean "it's not limiting the selection" as in "it's allowing the option for any file type"? If so, then try JFileChooser.setAcceptAllFileFilterUsed(boolean).

chooser.setAcceptAllFileFilterUsed(false);

According to the JFileChooser documentation, it should tell it not to add the all-file-types file filter to the file filter list.

like image 36
shieldgenerator7 Avatar answered Oct 10 '22 11:10

shieldgenerator7