Deselect a file in JFileChooser without closing the dialog

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); //if the user does not want to overwrite if (r == JOptionPane.NO_OPTION) { //cancel the selection of the current file chooser.setSelectedFile(null); } } } }); chooser.showSaveDialog(this); System.out.println(chooser.getSelectedFile()); } 

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?

+4
source share
2 answers

Override the approveSelection() method. Sort of:

 JFileChooser chooser = new JFileChooser( new File(".") ) { public void approveSelection() { if (getSelectedFile().exists()) { System.out.println("Do You Want to Overwrite File?"); // Display JOptionPane here. // if yes, super.approveSelection() } else super.approveSelection(); } }; 
+3
source

You may be able to reopen JFileChooser again if they do not want to overwrite the file.

The dialog will have the same directory as before, so the user does not need to navigate again.

0
source

Source: https://habr.com/ru/post/1479786/


All Articles