JFileChooser with confirmation dialog

前端 未结 5 907
忘掉有多难
忘掉有多难 2020-12-08 00:38

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.

This question is about

5条回答
  •  天涯浪人
    2020-12-08 01:16

    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.

提交回复
热议问题