![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e905. Listening for Approve and Cancel Events in a JFileChooser DialogWhen 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 With this deficiency, we recommend that you simply wait until
// 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); } }
e904. Listening for Changes to the Current Directory in a JFileChooser Dialog
© 2002 Addison-Wesley. |