Search code examples
javajoptionpane

show input dialog box after error message dialog box


I need to display an input dialog box and enter the player's name.

If the player clicked the ok button and the value of the input dialog is either a number or null an error should be displayed. If the player clicks the ok button of the error message dialog box, the input box will appear again.

I don't know if my code is wrong. I forgot how to code in java because of my web programming subject.

int[] player = new int[1];
for(int a =0; a<player.length; a++){
    String input = JOptionPane.showInputDialog("Enter your Name:",JOptionPane.OK_CANCEL_OPTION); 

    try {
        if(!input.matches("[a-zA-Z]+")){
            JOptionPane.showMessageDialog(null,"Use Letters only", "Warning", JOptionPane.OK_OPTION);    
        } else {
            input = String.valueOf(player[a]);
            category c = new category();
            this.dispose();
            c.show();
        }
    }
    catch(Exception e){   
};

Solution

  • If you do the loop right, you'll need only one dialog:

        String message = "Enter Your Name:";
        String playerName = null;
        do {
            playerName =
                JOptionPane.showInputDialog(message);
            message = "<html><b style='color:red'>Enter Your Name:</b><br>"
                    + "Use letters only.";          
        } while(playerName != null && !playerName.matches("[a-zA-Z]+"));
    
        System.out.println("PlayerName: " + playerName);
    

    This will include the error message into the next iteration of asking for a valid name. Makes it a bit nicer to work with as well.

    Shows like this on first call:

    first iteration

    and like this in case of errors:

    in case of errors

    Note

    You might want to change your regex to "[a-zA-Z]\\w+" if numbers later on in the name are okay (for instance "bunny99")