Java Swing How to - Handle action event for JFileChooser








Question

We would like to know how to handle action event for JFileChooser.

Answer

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

public class Main {
  public static void main(String[] args) {
    final JFileChooser chooser = new JFileChooser(new File(".")) {
      public void approveSelection() {
        if (getSelectedFile().exists()) {
          super.approveSelection();
        } else
          System.out.println("File doesn't exist");
      }
    };

    chooser.addActionListener(e -> System.out.println(e));

    chooser.setSelectedFile(new File("something.txt"));
    int returnVal = chooser.showSaveDialog(null);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
      System.out.println(chooser.getSelectedFile());
    }

  }
}