javaswingjfilechooser

How to listen to changes on 'File Name' TextField in JFileChooser?


I need to get the newest typed text inside text field labelled 'File name' in javax.swing.JFileChooser.

I don't need latest selected file because text typed into 'File name' should serve as a name for newly created file.

I used SELECTED_FILE_CHANGED_PROPERTY but it's fired only on file selections. There is also FILE_FILTER_CHANGED_PROPERTY but it is fired when I change type of file.

How to listen to changes of 'File Name' text field?

Thank you!


Solution

  • 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();
            }
        }
    }) ;