Search code examples
javaswingjoptionpanepropertychangelistener

Differentiating between no input (null String) and Cancel button in JOptionPane.showInputDialog()?


I am using an Input Dialog for user input. The input can be a string value, or simply pressing "OK" to use the default value. With this, there is no way to differentiate between the user specifying the default value (no string input, "OK" button press) and the user canceling ("Cancel" button press). Both return a null String.

It looks like I can register a PropertyChangeListener on the InputDialog, but that requires (apparently) constructing the InputDialog directly, then adding to a JDialog, etc. (all the stuff the JOptionPane does nicely in the background for me now.

Question: Is there some other way to differentiate between "OK" with a null value and "Cancel" without having to build the InputDialog myself and add the PropertyChangeListener?


Solution

  • You could use "" for the initialSelectionValue parameter to differentiate between OK and Cancel:

    String s = JOptionPane.showInputDialog(parent, "Enter a value", "");
    

    If the user clicked Cancel, s is null, if the user clicked OK and did not enter a value, it is "".