简体   繁体   中英

Java-Swing: Can't trap user into typing a correct filename

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");
    }
}

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM