The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing.filechooser  [19 examples] > Events  [3 examples]

e905. Listening for Approve and Cancel Events in a JFileChooser Dialog

When the user clicks on the approve button (Open or Save) or the Cancel button, an action event is fired.

Unfortunately, if the user clicks on the close-dialog icon in the title bar, an event is not fired. In order to listen for this event, it is necessary to add a window event listener to the dialog. This means that JFileChooser.showDialog() cannot be used because it creates the dialog internally. The workaround is to override the createDialog() method to make it public and then call it to create the dialog.

With this deficiency, we recommend that you simply wait until showDialog() returns and then use its return value. See e890 Determining If the Approve or Cancel Button Was Clicked in a JFileChooser Dialog for more information.

    // 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(frame);
    
    // 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);
            } 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);
        }
    });
    
    // Show the dialog; wait until dialog is closed
    dialog.show();
    
    // This version of JFileChooser simply makes createDialog a public method.
    public class MyFileChooser extends JFileChooser {
        public JDialog createDialog(Component parent) throws HeadlessException {
            return super.createDialog(parent);
        }
    }

 Related Examples
e903. Listening for Changes to the Selected File in a JFileChooser Dialog
e904. Listening for Changes to the Current Directory in a JFileChooser Dialog

See also: Hidden Files    Icons    Layout    Selections   


© 2002 Addison-Wesley.