Maria Khalid Maria Khalid - 7 months ago 39
Java Question

Handling of JOptionPane cancel button, which takes string as input

I want to take input as string from user through a Input dialog box, and also handle the situation if user presses cancel button.

Any suggestions?

Answer

You may use the showInputDialog method of class JOptionPane .

If the user hits Cancel, the returned value is null.

Also note, as @mKorbel said in the comments, that you will also get null if the windows has been closed directly.

String result = JOptionPane.showInputDialog("Please enter something");

if(result == null){


    System.out.println("User pressed CANCEL, or window has been closed");
}
else{

    // do something with the String
}