Maria Khalid Maria Khalid - 2 years ago 168
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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download