java - Cancel selecting a file within JFileChooser without closing the dialogue -
i trying implement "save as" dialogue using jfilechooser
. dialogue supposed give user ability type filename , click save, @ point new file
object returned , created.
this works, running problem when try add dialogue. specifically, want create "file exists" dialogue using joptionpane
warn user if trying create file same name pre-existing file (this common feature in many programs). dialogue prompts "file <filename> exists. replace it?" (yes/no)
. if user selects "yes", file object should returned normal. if user selects "no", jfilechooser
should stay open , await selection/creation of file.
the problem can't find way cancel selection (if user chooses "no") and keep dialogue open. have 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() + "\" exists.\nwould replace it?", "", joptionpane.yes_no_option); //if user not want overwrite if (r == joptionpane.no_option) { //cancel selection of current file chooser.setselectedfile(null); } } } }); chooser.showsavedialog(this); system.out.println(chooser.getselectedfile()); }
this cancels selection of file if user selects "no" (that selected file upon closure of dialogue null
). however, closes dialogue afterwards.
i prefer if dialogue remained open when happened. there way this?
override approveselection()
method. like:
jfilechooser chooser = new jfilechooser( new file(".") ) { public void approveselection() { if (getselectedfile().exists()) { system.out.println("do want overwrite file?"); // display joptionpane here. // if yes, super.approveselection() } else super.approveselection(); } };
Comments
Post a Comment