The Java Developers Almanac 1.4


Order this book from Amazon.

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

e903. Listening for Changes to the Selected File in a JFileChooser Dialog

A property change event is fired whenever the selected file is changed. However, the selected file can be null if the selected item does not match the selection mode of the chooser. For example, if the selection mode is JFileChooser.FILES_ONLY and a directory is selected, the fired event will have a new value of null.

Note: SELECTED_FILE_CHANGED_PROPERTY events are fired only if a single item is selected. In particular, if multiple items are selected while multiple-selection mode is enabled, this event is not fired. But if a single item is selected while in multiple-selection mode, this event is fired.

When in multiple-selection mode, SELECTED_FILES_CHANGED_PROPERTY events are always fired regardless of whether a single or multiple files have been selected.

    JFileChooser chooser = new JFileChooser();
    
    // Add listener on chooser to detect changes to selected file
    chooser.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY
                    .equals(evt.getPropertyName())) {
                JFileChooser chooser = (JFileChooser)evt.getSource();
                File oldFile = (File)evt.getOldValue();
                File newFile = (File)evt.getNewValue();
    
                // The selected file should always be the same as newFile
                File curFile = chooser.getSelectedFile();
            } else if (JFileChooser.SELECTED_FILES_CHANGED_PROPERTY.equals(
                    evt.getPropertyName())) {
                JFileChooser chooser = (JFileChooser)evt.getSource();
                File[] oldFiles = (File[])evt.getOldValue();
                File[] newFiles = (File[])evt.getNewValue();
    
                // Get list of selected files
                // The selected files should always be the same as newFiles
                File[] files = chooser.getSelectedFiles();
            }
        }
    }) ;

 Related Examples
e904. Listening for Changes to the Current Directory in a JFileChooser Dialog
e905. Listening for Approve and Cancel Events in a JFileChooser Dialog

See also: Hidden Files    Icons    Layout    Selections   


© 2002 Addison-Wesley.