Java Swing How to - Show custom Extension file on JFileChooser








Question

We would like to know how to show custom Extension file on JFileChooser.

Answer

import java.io.File;
// w  w  w  .  j  a  va  2 s  .  c om
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

class AudioFilter extends FileFilter {
  @Override
  public boolean accept(File f) {
    if (f.isDirectory()) {
      return true;
    }
    String extension = Utils.getExtension(f);
    if (extension != null) {
      if ((extension.equals(Utils.wav)) || (extension.equals(Utils.aif))
          || (extension.equals(Utils.rmf)) || (extension.equals(Utils.au))
          || (extension.equals(Utils.mid))) {
        return true;
      } else {
        return false;
      }
    }
    return false;
  }
  @Override
  public String getDescription() {
    return "wav, aif, rmf, au, mid";
  }

}

class Utils {
  public final static String wav = "wav";
  public final static String aif = "aif";
  public final static String rmf = "rmf";
  public final static String au = "au";
  public final static String mid = "mid";

  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 class Main {
  public static void main(String[] args) {
    AudioFilter audioFilter = new AudioFilter();

    JFileChooser jfc = new JFileChooser();

    jfc.setDialogTitle("Open File");
    jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    jfc.setCurrentDirectory(new File("."));
    jfc.setFileFilter(audioFilter);
    int result = jfc.showOpenDialog(null);

    if (result == JFileChooser.CANCEL_OPTION) {
      System.out.println("cancel");
    } else if (result == JFileChooser.APPROVE_OPTION) {
      File fFile = jfc.getSelectedFile();
      String filestr = fFile.getAbsolutePath();

      System.out.println(filestr);
    }
  }
}