tags:

views:

90

answers:

1

I'm writing a very simple text editor and have run into a somewhat minor problem. Code below

Saving a file, when a file exists, the user will be prompted to overwrite, cancel, or not overwrite (having the option to try again).

So I have a JFileChooser that will prompt the user to overwrite: yes, no, cancel

In the case of no being selected, it should return to the JFileChoose dialog, but I just plain don't know how. Can anyone help me out on this? The cancel and yes options aren't any problems (as far as I'm aware, haven't tested in depth)

String contents = textArea.getText();
   if (openPath != null) {
    savePath = openPath;     
   }
   else if (saveAsPath != null) {
    savePath = saveAsPath;
   }
   else if (savePath != null) {
    savePath = savePath;
   }
   else if (openPath == null) {
   JFileChooser saveFile = new JFileChooser();
   int returnVal = saveFile.showOpenDialog(null);
   if (returnVal == saveFile.APPROVE_OPTION) {
    savePath = saveFile.getSelectedFile();
    if (savePath.exists() != true) {
     FileWriter fstream = new FileWriter (savePath);
     BufferedWriter saveWrite = new BufferedWriter(fstream);
     saveWrite.write(contents);
     saveWrite.close();
    }
    else if (savePath.exists() == true) {
     JOptionPane overwritePrompt = new JOptionPane();
     Object[] options = {"Yes",
          "No",
          "Cancel"};
     int n = JOptionPane.showOptionDialog(overwritePrompt,
              "Already exists. Overwrite?",
              "Overwrite File?",
              JOptionPane.YES_NO_CANCEL_OPTION,
              JOptionPane.WARNING_MESSAGE,
              null,
              options,
              options[2]);
     if (n == 0) {
      FileWriter fstream = new FileWriter(saveAsPath);
      BufferedWriter out = new BufferedWriter(fstream);
      out.write(contents);
      out.close();
     }
     else if (n == 1) {
      savePath = null;
      openPath = null;
      saveAsPath = null;
      return; // should return to JFileChooser!!!!!!
     }
     else {
      savePath = null;
      openPath = null;
      saveAsPath = null;
      return;
     }
    }
   }
   else {
    return;
   }
A: 

What about starting over at this line:

int returnVal = saveFile.showOpenDialog(null);

again, when you should return to the JFileChooser? I assume that the same file chooser would display its open dialog again then?

Yngve Sneen Lindal
Wow, that sucks.Thanks man - Feels horrible destroying that code but you're dead right. I never looked much into JChooseFile - just went by example