Java Swing How to - Get Directories Only from JFileChooser








Question

We would like to know how to get Directories Only from JFileChooser.

Answer

import javax.swing.JFileChooser;
// w w w .  j  a  v a  2  s .  co  m
public class Main {
  public static void main(String[] args) {
    JFileChooser chooser = new JFileChooser();
    chooser.setMultiSelectionEnabled(false);
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int returnVal = chooser.showOpenDialog(null);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
      java.io.File f = chooser.getSelectedFile();
      System.err.println(f.getPath());
    }
  }
}