Java examples for Swing:JFileChooser
Listening for Approve and Cancel Events in a JFileChooser Dialog
import java.awt.Component; import java.awt.HeadlessException; import java.awt.event.ActionEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.AbstractAction; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; public class Main { public static void main(String[] argv) { // Create customized chooser MyFileChooser chooser = new MyFileChooser(); // Set dialog type if not OPEN_DIALOG chooser.setDialogType(JFileChooser.SAVE_DIALOG); // Create dialog containing the chooser final JDialog dialog = chooser.createDialog(new JFrame()); // Add listener for approve and cancel events chooser.addActionListener(new AbstractAction() { public void actionPerformed(ActionEvent evt) { JFileChooser chooser = (JFileChooser) evt.getSource(); if (JFileChooser.APPROVE_SELECTION.equals(evt.getActionCommand())) { // Open or Save was clicked // Hide dialog dialog.setVisible(false);//www. ja v a 2s. co m } else if (JFileChooser.CANCEL_SELECTION.equals(evt.getActionCommand())) { // Cancel was clicked // Hide dialog dialog.setVisible(false); } } }); // Add listener for window closing events dialog.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { // Close-dialog icon was clicked // Hide dialog dialog.setVisible(false); } }); dialog.show(); } } class MyFileChooser extends JFileChooser { public JDialog createDialog(Component parent) throws HeadlessException { return super.createDialog(parent); } }