I am trying to implement a Save As dialog using JFileChooser . The dialog should enable the user to enter a file name and click "Save", after which a new File object will be returned and created.
This works, but I have a problem when I try to add another dialog. In particular, I want to create a "File already exists" dialog using JOptionPane to warn the user if he tries to create a file with the same name as a previously existing file (this is a normal function in many programs). The dialog calls "File <filename> already exists. Would you like to replace it?" (Yes/No) "File <filename> already exists. Would you like to replace it?" (Yes/No) . If the user selects yes, the file object should be returned as usual. If the user selects "no", JFileChooser should remain open and wait for another file to be selected / created.
The problem is that I cannot find a way to deselect (if the user selects "no") and keeps the dialog open. I have a code:
public void saveAs() { if (editors.getTabCount() == 0) { return; } final JFileChooser chooser = new JFileChooser(); chooser.setMultiSelectionEnabled(false); chooser.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { File f = chooser.getSelectedFile(); if (f.exists()) { int r = JOptionPane.showConfirmDialog( chooser, "File \"" + f.getName() + "\" already exists.\nWould you like to replace it?", "", JOptionPane.YES_NO_OPTION);
This successfully deselects the file if the user selects "no" (this is the selected file when closing the null dialog). However, he also immediately closes the dialogue.
I would prefer the dialogue to remain open when this happened. Is there any way to do this?
source share