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());
...
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") ;
}
}
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With