adjust selected File to FileFilter in a JFileChooser

前端 未结 8 744
死守一世寂寞
死守一世寂寞 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条回答
  •  孤街浪徒
    2020-12-11 02:30

    It looks like you can listen to the JFileChooser for a change on the FILE_FILTER_CHANGED_PROPERTY property, then change the extension of the selected file appropriately using setSelectedFile().


    EDIT: You're right, this solution doesn't work. It turns out that when the file filter is changed, the selected file is removed if its file type doesn't match the new filter. That's why you're getting the null when you try to getSelectedFile().

    Have you considered adding the extension later? When I am writing a JFileChooser, I usually add the extension after the user has chosen a file to use and clicked "Save":

    if (result == JFileChooser.APPROVE_OPTION)
    {
      File file = fileChooser.getSelectedFile();
      String path = file.getAbsolutePath();
    
      String extension = getExtensionForFilter(fileChooser.getFileFilter());
    
      if(!path.endsWith(extension))
      {
        file = new File(path + extension);
      }
    }
    

    fileChooser.addPropertyChangeListener(JFileChooser.FILE_FILTER_CHANGED_PROPERTY, new PropertyChangeListener()
    {
      public void propertyChange(PropertyChangeEvent evt)
      {
        FileFilter filter = (FileFilter)evt.getNewValue();
    
        String extension = getExtensionForFilter(filter); //write this method or some equivalent
    
        File selectedFile = fileChooser.getSelectedFile();
        String path = selectedFile.getAbsolutePath();
        path.substring(0, path.lastIndexOf("."));
    
        fileChooser.setSelectedFile(new File(path + extension));
      }
    });
    

提交回复
热议问题