Reputation: 131
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());
...
Upvotes: 13
Views: 27942
Reputation: 1080
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") ;
}
}
});
Upvotes: 13
Reputation: 1736
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.
Upvotes: 2
Reputation: 2258
Here is a sample code!
private void btnChangeFileActionPerformed(java.awt.event.ActionEvent evt) {
final JFileChooser fc = new JFileChooser();
fc.addChoosableFileFilter(new ArffFilter());
int returnVal = fc.showOpenDialog(this);
...
}
Then
class ArffFilter extends FileFilter {
@Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
}
String fileName = file.getName();
int i = fileName.lastIndexOf('.');
if (i > 0 && i < fileName.length() - 1) {
if (fileName.substring(i + 1).toLowerCase().equals("arff")) {
return true;
}
}
return false;
}
@Override
public String getDescription() {
return ".arff (Weka format)";
}
}
Upvotes: 0
Reputation: 11
Try to use fileChooser.setFileFilter(filter)
after fileChooser.addChoosableFileFilter(filter)
, because you need to add your filter
to fileChooser
and then setting it as default value.
Here is the link with good example: http://www.java2s.com/Code/Java/Swing-JFC/CustomizingaJFileChooser.htm
Upvotes: 1
Reputation: 21
Try and use fileChooser.setFileFilter(filter)
instead of fileChooser.addChoosableFileFilter(filter)
.
Upvotes: 1