adjust selected File to FileFilter in a JFileChooser

前端 未结 8 734
死守一世寂寞
死守一世寂寞 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:40

    Here's my attempt at this. It uses the accept() function to check whether or not the file passes the filter. If the filename does not, the extension is appended to the end.

    JFileChooser jfc = new JFileChooser(getFile()) {
            public void approveSelection() {
                if (getDialogType() == SAVE_DIALOG) {
                    File selectedFile = getSelectedFile();
    
                    FileFilter ff = getFileFilter();
    
                    // Checks against the current selected filter
                    if (!ff.accept(selectedFile)) {
                        selectedFile = new File(selectedFile.getPath() + ".txt");
                    }
                    super.setSelectedFile(selectedFile);
    
                    if ((selectedFile != null) && selectedFile.exists()) {
                        int response = JOptionPane.showConfirmDialog(
                                this,
                                "The file " + selectedFile.getName() + " already exists.\n" +
                                "Do you want to replace it?",
                                "Ovewrite file",
                                JOptionPane.YES_NO_OPTION,
                                JOptionPane.WARNING_MESSAGE
                        );
                        if (response == JOptionPane.NO_OPTION)
                            return;
                    }
                }
                super.approveSelection();
            }
        };
    

提交回复
热议问题