0

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Maria Khalid
  • 189
  • 2
  • 15
  • 2
    see `JOptionPane.showInputDialog` . https://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html#showInputDialog(java.awt.Component,%20java.lang.Object) . `null` is returned if the user chooses "Cancel" . – Arnaud May 02 '16 at 13:58
  • @Berger How about upgrading that comment to an answer? – Andrew Thompson May 02 '16 at 14:11
  • Why even SO community try to answer questions like that. Those type of question asked millions of times and still getting answers.. Just google your question. – Y.Kaan Yılmaz May 02 '16 at 14:29

2 Answers2

2

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
}
Arnaud
  • 17,229
  • 3
  • 31
  • 44
  • disagree, because `result != null`, `JOptionPane` has all `windows events` implemented in API (closing, event from escape key, .....) – mKorbel May 03 '16 at 08:26
  • @mKorbel : That's right, but will you agree that getting `null` at least means that the `Ok` button wasn't chosen ? – Arnaud May 03 '16 at 08:34
  • [there is something that I ....e.g. :-)](http://stackoverflow.com/a/8582851/714968) – mKorbel May 03 '16 at 08:37
1

Try this:

if(result == null){
    System.out.println("User pressed CANCEL, or window has been closed");
    System.exit(0);
}
Hexfire
  • 5,945
  • 8
  • 32
  • 42