9

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.

burntsugar
  • 57,360
  • 21
  • 58
  • 81

4 Answers4

14

Check if selectedSiteName == null .
This will be the case if the user clicks Cancel or closes the dialog.

Jataro
  • 2,548
  • 1
  • 17
  • 17
0

Read the JOptionPane API and follow the link to the Swing turorial on "How to Use Dialogs" for a working example.

camickr
  • 321,443
  • 19
  • 166
  • 288
0
if(selectedSiteName == JOptionPane.CANCEL_OPTION)
{


}

should work.

Nick Gibson
  • 155
  • 1
  • 3
  • 10
0

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