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.
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()).
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.
JFileChooser. setMultiSelectionEnabled(true) − To enable the multiple selection of file.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With