Reputation: 359
Is it possible in JFileChooser to have the FileFilter with wildcards ?
When File browser opens I want the user to select a specific file like *_SomeFixedFormat.def file among all *.def files.
With FileNameExtensionFilter I'm able to do it for .def files but not for this specific file.
FileNameExtensionFilter fileFilter=new FileNameExtensionFilter(".def", "def");
fileChooser.setFileFilter(fileFilter);
Upvotes: 0
Views: 1661
Reputation: 764
Usage
DefFileFilter fileFilter=new DefFileFilter (new String[] {"DEfFile1"});
fileChooser.setFileFilter(fileFilter);
Filter
package ui.filechooser.filter;
import java.io.File;
import javax.swing.filechooser.FileFilter;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.io.FilenameUtils;
/**
*
* @author Igor
*/
public class DefFileFilter extends FileFilter {
public final static String DEF_EXT = "def";
//def file name example : "DEfFile1", "DefFile2" ....
private String[] allowedNames;
public DefFileFilter() {
this(null);
}
public DefFileFilter(String names[]) {
this.allowedNames = name;
}
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
String extension = getExtension(f);
if (extension != null) {
if (extension.equals(DEF_EXT)) {
if(allowedNames != null && !StringUtils.indexOfAny(getBaseName(f.getName), allowedNames)) {
return false;
} else {
return true;
}
} else {
return false;
}
}
return false;
}
public static String getBaseName(String fileName) {
int index = fileName.lastIndexOf('.');
if (index == -1) {
return fileName;
} else {
return fileName.substring(0, index);
}
}
public static String getExtension(File f) {
String ext = null;
String s = f.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1) {
ext = s.substring(i + 1).toLowerCase();
}
return ext;
}
public String getDescription() {
return "Excel file";
}
}
Upvotes: 0
Reputation: 4039
Create your own FileFilter
JFileChooser fc = new JFileChooser();
fc.setFileFilter(new FileFilter(){
@Override
public boolean accept(File file){
// always accept directorys
if(file.isDirectory())
return true;
// but only files with specific name _SomeFixedFormat.def
return file.getName().equals("_SomeFixedFormat.def");
}
@Override
public String getDescription() {
return ".def";
}
});
Upvotes: 3
Reputation: 539
Change the FileNameExtensionFilter(".def", def);
to FileNameExtensionFilter(".def", "_yourFixedFormat.def");
. I am not sure if this works. If not, restrict it only to .def, and when you choose a file, check if name of the file equals to your format, if not, open JFileChooser again.
Upvotes: 1