首页javajfilechooserJava Swing - 如何处理JFileChooser的动作事件

Java Swing - 如何处理JFileChooser的动作事件

我们想知道如何处理JFileChooser的动作事件。
import java.io.File;

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());
    }

  }
}