简体   繁体   中英

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!

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

What you want is a JFileChooser with the SAVE_DIALOG Flag.

Some demo code:

JFileChooser chooser = new JFileChooser("some path");
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
// Stuff like setting the required file extension, the title, ...
int result = chooser.showSaveDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
    String path = chooser.getSelectedFile().toString();
    // Do something with the path
}
chooser.setVisible(false); // Don't forget to hide

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM