dontHaveName
dontHaveName

Reputation: 1937

java text dialog, which button was clicked?

I followed official guide for java dialogs so I have this code:

String s = JOptionPane.showInputDialog(this, "Text\n\nEnter your name", "Heading", JOptionPane.PLAIN_MESSAGE);

How can I check if an user clicked OK or cancel button?

Upvotes: 2

Views: 1745

Answers (2)

Katarak
Katarak

Reputation: 79

showInputDialog:

Returns:
user's input, or null meaning the user canceled the input

If method call returns null, then the user pressed cancel. Otherwise, if he pressed ok, it will contain the user input.

Upvotes: 2

Rahul Tripathi
Rahul Tripathi

Reputation: 172398

Try this:

String input = JOptionPane.showInputDialog(this, "Text\n\nEnter your name", "Heading", JOptionPane.PLAIN_MESSAGE);
if (input!=null) { ....}

Note that when the user clicks on "cancel", input will be null.

So you can try like this if you want to check if the user clicks Cancel or OK button

String input = JOptionPane.showInputDialog(this, "Text\n\nEnter your name", "Heading", JOptionPane.PLAIN_MESSAGE);
if (input != null) { 
 // functionality for the OK button click
} else {
 // functionality for the Cancel button click
}

Upvotes: 3

Related Questions