Java Swing How to - Handle action result from JFileChooser








Question

We would like to know how to handle action result from JFileChooser.

Answer

import java.io.File;
//from   w ww.  j a v a  2s  .c o m
import javax.swing.JFileChooser;

public class Main {
  public static void main(String[] args) {
    String path = System.getProperty("user.dir", ".");

    File dir = new File(path);

    JFileChooser jfc = new JFileChooser(dir);
    int result = jfc.showOpenDialog(null);

    switch (result) {
    case JFileChooser.CANCEL_OPTION:
      System.out.println("User cancelled OPEN dialog.");
      break;
    case JFileChooser.APPROVE_OPTION:
      System.out.println("User chose file: " + jfc.getSelectedFile());
      break;
    case JFileChooser.ERROR_OPTION:
      System.out.println("User encountered an error");
      break;
    default:
      System.out.println("Confused");
      break;
    }

    System.exit(0);
  }
}