Overwrite files with the JFileChooser

Tags:

1. November 2007

To check if the user wants to overwrite the file he has selected in the JFileChooser, you have to implement the test usualy outside of the JFileChooser.
With a little bit of subclassing you can add a message dialog which handles the overwrite confirmation inside of the JFileChooser.

JFileChooser fileChooser = new JFileChooser() {
   @Override
   public void approveSelection() {
       File selectedFile = getSelectedFile();
 
       if(selectedFile.exists()) {
           int result = JOptionPane.showConfirmDialog(this,
                   "The file you've selected already exists!\n" +
                   "Do you really want to overwrite?",
                   "Overwrite file",
                   JOptionPane.YES_NO_OPTION);
           if(result == JOptionPane.YES_OPTION) {
               super.approveSelection();
           }
       } else {
           super.approveSelection();
       }
   }
};

Everytime the user clicks the save button in the dialog, the approveSelection()-method is called. As you see above, the subclassing overwrites this method and adds a check if the selected file is already existing. If yes, a confirmation dialog appears where the user can make his decision if he wants to overwrite or not.

Very simple, isn’t it?

Ihre Meinung dazu






 

Bereit? Dann...