Filter for JFileChooser


/ Published in: Java
Save to your folder(s)



Copy this code and paste it in your HTML
  1. import javax.swing.filechooser.FileFilter;
  2. import java.io.File;
  3.  
  4. public class Filter extends FileFilter {
  5. private boolean acceptDirs = true;
  6. private String desc;
  7. private String ext;
  8.  
  9. public Filter(String ext) {
  10. this.ext = ext;
  11. this.desc = ext + "-Files (" + generateExtensionString(ext) + ")";
  12. }
  13.  
  14. public Filter(String ext, String desc) {
  15. this.ext = ext;
  16. this.desc = desc + " (" + generateExtensionString(ext) + ")";
  17. }
  18.  
  19. public String getDescription() {
  20. return desc;
  21. }
  22.  
  23. public boolean accept(File f) {
  24. if (f.isDirectory() && acceptDirs) {
  25. return true;
  26. }
  27.  
  28. if (!isMultiExtensionString(ext)) {
  29. return f.getName().endsWith(ext);
  30. }
  31.  
  32. String[] exts = ext.split(",");
  33.  
  34. for (int i = 0; i < exts.length; i++) {
  35. if (f.getName().endsWith(exts[i])) {
  36. return true;
  37. }
  38. }
  39.  
  40. return false;
  41. }
  42.  
  43. protected boolean isMultiExtensionString(String ext) {
  44. return ext.indexOf(',') >= 0;
  45. }
  46.  
  47. protected String generateExtensionString(String ext) {
  48. String[] exts = ext.split(",");
  49.  
  50. for (int i = 0; i < exts.length; i++) {
  51. sb.append("*.");
  52. sb.append(exts[i]);
  53.  
  54. if (i != exts.length - 1) {
  55. sb.append(",");
  56. }
  57. }
  58.  
  59. return sb.toString();
  60. }
  61. }
  62.  

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.