I'm unsure of best practices with JOptionPanes, though this could equally just be a logic problem. I want an input box that asks for a name, checks it is a letter only string, and user can cancel.
I understand that cancelling a JOptionPane results in returning a null, which I've implemented at the start. The issue is that if a user enters incorrectly in the first pane, they cannot cancel from the second.
EDIT: worth pointing out that if user cancels I don't want to do anything with the name. This is the issue that forces me into the loop. Logic should be to check user input; if ==2 do nothing. If something else, validate is a word and use it. Loop around if not valid. The problem is the user can cancel later and the action of using the name is actioned anyway since it's in the second loop, with the value of 2.
I currently have:
JOptionPane optionPane1 = new JOptionPane(text, OK_OPTION, CANCEL_OPTION);
optionPane1.setWantsInput(true);
JDialog d1 = optionPane1.createDialog(null);
d1.setVisible(true);
name = optionPane1.getInputValue().toString();
if(name == null){
gamePaused = true;
}
else{
while(!name.matches("^[a-zA-Z]+$") || name.length() == 0){
JOptionPane optionPane2 = new JOptionPane("Please enter a word.\nTry again.", OK_OPTION, CANCEL_OPTION);
optionPane2.setWantsInput(true);
JDialog d2 = optionPane2.createDialog(null);
d2.setVisible(true);
name = optionPane2.getInputValue().toString();
}
///use name
}
Is there a better way of doing this, so that I can allow a user to cancel and escape the loop?