带有确认对话框的JFileChooser [英] JFileChooser with confirmation dialog

查看:134
本文介绍了带有确认对话框的JFileChooser的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

有关如何解决此问题的任何建议吗?我一直在寻找一些方法或选项,但我没有找到任何东西。

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

提前致谢。

推荐答案

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

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

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.

这篇关于带有确认对话框的JFileChooser的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆