Java Swing How to - Detect Approval button in a Swing FileChooser event








Question

We would like to know how to detect Approval button in a Swing FileChooser event.

Answer

//from w ww. ja v  a  2 s  . com
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.WindowConstants;

public class Main {
  public JComponent makeUI() {
    final JPanel p = new JPanel();
    final JFileChooser fileChooser = new JFileChooser() {
      @Override
      public void approveSelection() {
        if (!getSelectedFile().exists()) {
          int returnVal = JOptionPane.showConfirmDialog(this, "message",
              "title", JOptionPane.YES_NO_OPTION);
          if (returnVal != JOptionPane.YES_OPTION) {
            return;
          }
        }
        super.approveSelection();
      }
    };
    p.add(new JButton(new AbstractAction("Open") {
      @Override
      public void actionPerformed(ActionEvent e) {
        int retvalue = fileChooser.showOpenDialog(p);
        if (retvalue == JFileChooser.APPROVE_OPTION) {
          System.out.println(fileChooser.getSelectedFile());
        }
      }
    }));
    return p;
  }

  public static void main(String[] args) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    f.getContentPane().add(new Main().makeUI());
    f.setSize(320, 240);
    f.setVisible(true);
  }
}