0

I'm trying to trap a user into typing a correct file name unless he presses cancel or X. But if he does cancel the input my program throws a NullPointerException.

public void openSaveAsDirectory() {

    JDialog dialog = new JDialog();
    dialog.setTitle("Save file as");
    String name = JOptionPane.showInputDialog(adTable, "Please type a name for your file");
    if(name != null && !name.isEmpty()) {

        File fileName = new File(SAVE_LOCATION + FILE_SEPERATOR + name + FILE_SUFFIX);
        book.saveUser(fileName);

    }

    while(name.isEmpty()) {
            name = JOptionPane.showInputDialog(adTable, "Please type a name for your file");
    }
}
lucas6198
  • 35
  • 4

1 Answers1

0

Based on your comment, here is an updated version that asks for an input as long as it is empty but stops, when the user hits the cancel button.

String name;
do {
    name = JOptionPane.showInputDialog(null, "Please type a name for your file");
    if(name == null) { //user hit cancel, break the loop
        break;
    }
} while(name.isEmpty());
Tobias Geiselmann
  • 2,139
  • 2
  • 23
  • 36
  • Wouldn't this just trap a user forever? Because while name==null only occurs if the user presses cancel or X if I'm not mistaken. But I want the user to be able to cancel the input. – lucas6198 Sep 27 '17 at 13:00
  • Correct, that would keep asking forever. You never stated that you want it to stop, when the user cancels (although it makes perfect sense!). – Tobias Geiselmann Sep 27 '17 at 13:03
  • My fault I'm not good at expressing myself in english :/ I want him to be able to cancel the input. – lucas6198 Sep 27 '17 at 13:06