How to handle cancel button in JOptionPane

Viewed 78572

I had created a JOptionPane of type showInputDialog. When it opens it, it shows me two buttons: OK and Cancel. I would like to handle the action when I push on Cancel button, but I don't know how to reach it. How can I get it?

7 Answers

You could do it like this:

String val = JOptionPane.showInputDialog("Value: ");
if(val == null){
  // nothing goes here if yo don't want any action when canceled, or
  // redirect it to a cancel page if needed
}else{
  //insert your code if ok pressed
  // JOptionPane return an String, as you was talking about int
  int value = Integer.ParseInt(val);
}

showInputDialog return NULL if you click cancel and String object even if it's empty. So all you need to do is test if it's Null and if it's not empty.

Related