Get the return value of JOptionPane
-
06-07-2019 - |
Question
My JOptionPane code is as follows:
selectedSiteName = JOptionPane.showInputDialog("Enter the name of the new site:");
This renders out an input with a textbox and an OK and Cancel button. I need to detect if Cancel was clicked.
Cheers.
Solution
Check if selectedSiteName == null .
This will be the case if the user clicks Cancel or closes the dialog.
OTHER TIPS
Read the JOptionPane API and follow the link to the Swing turorial on "How to Use Dialogs" for a working example.
if(selectedSiteName == JOptionPane.CANCEL_OPTION)
{
}
should work.
JOptionPane extends JComponent.
Methods of JOptionPane
1) .showMessageDialog(); // VOID :-(
2) .showInputDialog(); // return STRING :-)
3) .showConfirmDialog(); // return int :-)
-> and more...
Example:
void myMethod() {
JDialog jd = new JDialog();
jd.setDefaultCloseOperation(1);
JOptionPane jop = new JOptionPane();
int val = jop.showConfirmDialog(jd, "Hello");
if(val == 0) jop.showMessageDialog(null, "Success", "INFO", jop.INFORMATION_MESSAGE);
System.out.println(val);
jd.add(jop);
}
Helpful link:
- Why does JOptionPane.getValue() continue to return uninitializedValue
- https://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html