1

I have a custom dialog box that collects two strings from the user. I use OK_CANCEL_OPTION for the option type when creating the dialog. Evertyhings works except when a user clicks cancel or closes the dialog it has the same effect has clicking the OK button.

How can i handle the cancel and close events?

Heres the code I'm talking about:

JTextField topicTitle = new JTextField();
JTextField topicDesc = new JTextField();
Object[] message = {"Title: ", topicTitle, "Description: ", topicDesc};
JOptionPane pane = new JOptionPane(message,  JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
JDialog getTopicDialog =  pane.createDialog(null, "New Topic");
getTopicDialog.setVisible(true);

// Do something here when OK is pressed but just dispose when cancel is pressed.

/Note: Please Don't Suggest me the way of JOptionPane.ShowOptionDialog(*****);** for this issue because i know that way but i need above mentioned way of doing and setting actions for "OK" and "CANCEL" buttons.*/

assylias
  • 321,522
  • 82
  • 660
  • 783
Sekhar
  • 53
  • 1
  • 2
  • 11

2 Answers2

4

This works for me:

...
JOptionPane pane = new JOptionPane(message,  JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
JDialog getTopicDialog =  pane.createDialog(null, "New Topic");
getTopicDialog.setVisible(true);
if(null == pane.getValue()) {
    System.out.println("User closed dialog");
}
else {
    switch(((Integer)pane.getValue()).intValue()) {
    case JOptionPane.OK_OPTION:
        System.out.println("User selected OK");
        break;
    case JOptionPane.CANCEL_OPTION:
        System.out.println("User selected Cancel");
        break;
    default:
        System.out.println("User selected " + pane.getValue());
    }
}
fzborrego
  • 101
  • 2
1

According to the documentation you can use pane.getValue() to know which button was clicked. From documentation:

Direct Use: To create and use an JOptionPane directly, the standard pattern is roughly as follows:

     JOptionPane pane = new JOptionPane(arguments);
     pane.set.Xxxx(...); // Configure
     JDialog dialog = pane.createDialog(parentComponent, title);
     dialog.show();
     Object selectedValue = pane.getValue();
     if(selectedValue == null)
       return CLOSED_OPTION;
     //If there is not an array of option buttons:
     if(options == null) {
       if(selectedValue instanceof Integer)
          return ((Integer)selectedValue).intValue();
       return CLOSED_OPTION;
     }
     //If there is an array of option buttons:
     for(int counter = 0, maxCounter = options.length;
        counter < maxCounter; counter++) {
        if(options[counter].equals(selectedValue))
        return counter;
     }
     return CLOSED_OPTION;

Hope it helps,

Esteban Aliverti
  • 6,259
  • 2
  • 19
  • 31