Java 带有确认对话框的 JFileChooser

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3651494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 03:10:51  来源:igfitidea点击:

JFileChooser with confirmation dialog

javaswingconfirmation

提问by Roberto Luis Bisbé

I am working on a program that loads and saves data from text files, and I am asking the user a file name with JFileChooser on load and save.

我正在开发一个从文本文件加载和保存数据的程序,我在加载和保存时使用 JFileChooser 询问用户一个文件名。

This question is about the savedialog: new JFileChooser().showSaveDialog();. The user then could overwrite an existing file without any warning, and that would be a problem.

这个问题是关于保存对话框的:new JFileChooser().showSaveDialog();。然后用户可以在没有任何警告的情况下覆盖现有文件,这将是一个问题

Any suggestion on how to fix this? I have been looking for some method or option, but I didn't found anything.

关于如何解决这个问题的任何建议?我一直在寻找某种方法或选项,但没有找到任何东西。

Thanks in advance.

提前致谢。

采纳答案by Roberto Luis Bisbé

Thanks for the answers, but I found another workaround, overriding the approveSelection() of the JFileChooser, this way:

感谢您的回答,但我找到了另一种解决方法,以这种方式覆盖 JFileChooser 的批准选择():

JFileChooser example = new JFileChooser(){
    @Override
    public void approveSelection(){
        File f = getSelectedFile();
        if(f.exists() && getDialogType() == SAVE_DIALOG){
            int result = JOptionPane.showConfirmDialog(this,"The file exists, overwrite?","Existing file",JOptionPane.YES_NO_CANCEL_OPTION);
            switch(result){
                case JOptionPane.YES_OPTION:
                    super.approveSelection();
                    return;
                case JOptionPane.NO_OPTION:
                    return;
                case JOptionPane.CLOSED_OPTION:
                    return;
                case JOptionPane.CANCEL_OPTION:
                    cancelSelection();
                    return;
            }
        }
        super.approveSelection();
    }        
}

I hope this could be useful for someone else.

我希望这对其他人有用。

回答by Jigar Joshi

Check before saving if the same file already exist then ask user for confirmation does she really want to override :p

在保存之前检查相同的文件是否已经存在然后询问用户确认她是否真的想覆盖:p

 JDialog.setDefaultLookAndFeelDecorated(true);
    int response = JOptionPane.showConfirmDialog(null, "Are you sure you want to override existing file?", "Confirm",
        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
    if (response == JOptionPane.NO_OPTION) {
      System.out.println("No button clicked");
    } else if (response == JOptionPane.YES_OPTION) {
      System.out.println("Yes button clicked");
    } else if (response == JOptionPane.CLOSED_OPTION) {
      System.out.println("JOptionPane closed");
    }  

hereis code

是代码

To check file already exist use

要检查文件已存在,请使用

boolean exists = (new File("filename")).exists();
if (exists) {
    // File or directory exists
} else {
    // File or directory does not exist
}

回答by Riduidel

Maybe you could verify that the file does not already exists, and even give the JFileChooser a FileSystemView(see this constructor)

也许你可以验证文件不存在,甚至给 JFileChooser 一个FileSystemView(见这个构造函数

回答by matt burns

I wrote this based on your own answer. Posted in case someone else finds it useful:

我是根据你自己的回答写的。发布以防其他人发现它有用:

final JFileChooser exportFileChooser = new JFileChooser();
exportFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
exportFileChooser.setApproveButtonText("Export");

final JButton exportButton = new JButton("Export text file");
exportButton.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        int returnVal = exportFileChooser.showSaveDialog(exportButton
                .getParent());

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File outputFile = exportFileChooser.getSelectedFile();
            if (outputFileIsValid(outputFile)) {
                exportFile(outputFile);
            }
        }
    }

    private boolean outputFileIsValid(File outputFile) {
        boolean fileIsValid = false;
        if (outputFile.exists()) {
            int result = JOptionPane.showConfirmDialog(
                    exportButton.getParent(),
                    "File exists, overwrite?", "File exists",
                    JOptionPane.YES_NO_CANCEL_OPTION);
            switch (result) {
            case JOptionPane.YES_OPTION:
                fileIsValid = true;
                break;
            default:
                fileIsValid = false;
            }
        } else {
            fileIsValid = true;
        }
        return fileIsValid;
    }
});

回答by kmindi

As AvrDragon said, closing with X is not handled. I added a default case to handle all unrelevant options:

正如 AvrDragon 所说,不处理 X 关闭。我添加了一个默认情况来处理所有不相关的选项:

final JFileChooser fc = new JFileChooser() {

        private static final long serialVersionUID = 7919427933588163126L;

        public void approveSelection() {
            File f = getSelectedFile();
            if (f.exists() && getDialogType() == SAVE_DIALOG) {
                int result = JOptionPane.showConfirmDialog(this,
                        "The file exists, overwrite?", "Existing file",
                        JOptionPane.YES_NO_CANCEL_OPTION);
                switch (result) {
                case JOptionPane.YES_OPTION:
                    super.approveSelection();
                    return;
                case JOptionPane.CANCEL_OPTION:
                    cancelSelection();
                    return;
                default:
                    return;
                }
            }
            super.approveSelection();
        }
    };