且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

带有确认对话框的JFileChooser

更新时间:2023-01-24 12:49:27

感谢您的回答,但我找到了另一种解决方法,以这种方式覆盖了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.