adjust selected File to FileFilter in a JFileChooser

前端 未结 8 730
死守一世寂寞
死守一世寂寞 2020-12-11 02:22

I\'m writing a diagram editor in java. This app has the option to export to various standard image formats such as .jpg, .png etc. When the user clicks File->Export, you get

8条回答
  •  Happy的楠姐
    2020-12-11 02:51

    Here is a method to obtain the current file name (as a String). In your property change listener for JFileChooser.FILE_FILTER_CHANGED_PROPERTY, you make the following call:

    final JFileChooser fileChooser = new JFileChooser();
    fileChooser.addPropertyChangeListener(JFileChooser.FILE_FILTER_CHANGED_PROPERTY, new PropertyChangeListener()
    {
        @Override
        public void propertyChange(PropertyChangeEvent e) {
            String currentName = ((BasicFileChooserUI)fileChooser.getUI()).getFileName();
            MyFileFilter filter = (MyFileFilter) e.getNewValue();
    
            // ... Transform currentName as you see fit using the newly selected filter.
            // Suppose the result is in newName ...
    
            fileChooser.setSelectedFile(new File(newName));
        }
    });
    

    The getFileName() method of javax.swing.plaf.basic.BasicFileChooserUI (the descendant of FileChooserUI returned by JFileChooser.getUI()) will return the contents of the dialog's text box that is used to type in the file name. It seems that this value is always set to a non-null String (it returns an empty string if the box is empty). On the other hand, getSelectedFile() returns null if the user has not selected an existing file yet.

    It seems that the dialog's design is governed by the 'file selection' concept; that is, while the dialog is visible getSelectedFile() only returns a meaningful value if the user has already selected an existing file or the program called setSelectedFile(). getSelectedFile() will return what the user typed in after the user clicks the approve (i.e. OK) button.

    The technique will only work for single-selection dialogs, however changing file extension based on selected filter should also make sense for single files only ("Save As..." dialogs or similar).

    This design was a subject of a debate at sun.com back in 2003, see the link for details.

提交回复
热议问题