I am putting a JFileChooser
in my program, but that only takes images. So I decided to add filters:
import javax.swing.*;
public c
the argument of fc.addChoosableFileFilter()
should be a subclass of javax.swing.filechooser.FileFilter
. For example, you can change your code as
fc.addChoosableFileFilter(new FileNameExtensionFilter("Image Files", "jpg", "png", "tif");
You are using wrong ImageFiler class :-)
The ImageFilter from tutorial is not from java.awt package you are importing. This ImageFilter must implement javax.swing.filechooser.FileFilter.
Please check if there is other ImageFilter class defined in tutorial and use it.
Example of proper filefilter:
new JFileChooser().addChoosableFileFilter(new FileFilter() {
@Override
public boolean accept(File f) {
// TODO Auto-generated method stub
return f.getName().endsWith(".jpg");
}
@Override
public String getDescription() {
return "JPEG files";
}
});
You can use FileFilter
class and then use setFileFilter()
class ImageFilter extends FileFilter {
@Override
public boolean accept(File pathname) {
String filename = pathname.getName();
if (pathname.isDirectory()) {
return true;
} else if (filename.endsWith("jpg'") || filename.endsWith("jpeg") || filename.endsWith("png") || filename.endsWith("gif")) {
return true;
} else {
return false;
}
}
Now in your main class:
fc.setFileFilter(new ImageFilter());
The accepted answer (using FileNameExtensionFilter with ImageIO.getReaderFileSuffixes()) has some problems.
On my system (jdk1.8.0_192 on Ubuntu) ImageIO.getReaderFileSuffixes() returns an array like this:
[, jpg, tiff, bmp, pcx, gif, png, ppm, tif, pgm, wbmp, jpeg, pbm]
Note the first empty String. This String is not valid in FileNameExtensionFilter:
IllegalArgumentException: Each extension must be non-null and not empty
A solution to this would be to remove the empty String - using Apache commons-lang:
String[] extensions = ArrayUtils.removeAllOccurences(ImageIO.getReaderFileSuffixes(), "");
FileFilter filter = new FileNameExtensionFilter("Images", extensions);
On a side note - on the same system with openjdk version "11.0.2" 2019-01-15 I get these extensions:
[jpg, tif, tiff, bmp, gif, png, wbmp, jpeg]
i am using setFileFilter().
My Code is Below (JAVA-JSE 1.6)
JFileChooser c = new JFileChooser();
//Setting Up The Filter
FileFilter imageFilter = new FileNameExtensionFilter(
"Image files", ImageIO.getReaderFileSuffixes());
//Attaching Filter to JFileChooser object
c.setFileFilter(imageFilter);
//Displaying Filechooser
int rVal = c.showOpenDialog(new JPanel());
I am putting a JFileChooser in my program, but that only takes images.
For a list of types supported by that JRE on that OS, use ImageIO.
FileFilter imageFilter = new FileNameExtensionFilter(
"Image files", ImageIO.getReaderFileSuffixes());
bmp
jpg
jpeg
wbmp
png
gif
Note: don't hard-code that list! It might change from version to version, and OS to OS. E.G.
That list would have many more formats if jai was installed.