Maria Khalid Maria Khalid - 5 months ago 23x
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?


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

    // do something with the String