Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JFileChooser with confirmation dialog

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 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.

Thanks in advance.

like image 589
Roberto Luis Bisbé Avatar asked Sep 06 '10 12:09

Roberto Luis Bisbé


People also ask

How do I find my JFileChooser file name?

JFileChooser has a method, getSelectedFile(). Which is a File. If you open the dialog with showSaveDialog() you should be able to get the File from that (file. getName()).

What is the main purpose of using JFileChooser?

As you have seen, the JFileChooser class provides the showOpenDialog method for displaying an open dialog and the showSaveDialog method for displaying a save dialog. The class has another method, showDialog , for displaying a file chooser for a custom task in a dialog.

How do I select multiple files in JFileChooser?

JFileChooser. setMultiSelectionEnabled(true) − To enable the multiple selection of file.

What is a JFileChooser?

JFileChooser is a part of java Swing package. The java Swing package is part of JavaTM Foundation Classes(JFC) . JFC contains many features that help in building graphical user interface in java . Java Swing provides components such as buttons, panels, dialogs, etc .


1 Answers

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.

like image 137
Roberto Luis Bisbé Avatar answered Sep 21 '22 04:09

Roberto Luis Bisbé