Reputation: 1283
I have a custom JDialog that I made in order to solve some local problems (RTL etc') until now, it only had an "ok" option, I have to modify it now to also have a cancel button. I did that. the only problem now is that I don't know how to get the input from it, was OK pressed or Cancel ?
please help.
this is my code:
public MyDialog(String title,boolean withCancelButton) {
String message = "<html><b><font color=\"#8F0000\" size=\"7\" face=\"Ariel\">" + title + "</font></p></html>";
JOptionPane pane = new JOptionPane(message, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
JDialog dialog = pane.createDialog(null, title);
dialog.setVisible(true);
dialog.dispose();
if (pane.getOptionType() == 1)
okWasPressed = true;
else
okWasPressed = false;
}
the thing is that pane.getOptionType() always return "2", so its probably the options count or something.
how can I get to the actual selection ?
thanks, Dave.
Upvotes: 0
Views: 441
Reputation: 3809
The easiest option is to use the standard functionality, like this:
int opt = JOptionPane.showOptionDialog(jf, "Do you really want to?", "Confirm",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
if(opt == JOptionPane.OK_OPTION) {
System.out.println("Ok then!");
} else {
System.out.println("Didn't think so.");
}
If you really want to use your own dialog, as in the example, you should use getValue() to check what was pressed:
JOptionPane optionPane = new JOptionPane("Do you really want to?",
JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
JDialog dialog = optionPane.createDialog(jf, "Confirm");
dialog.setVisible(true);
dialog.dispose();
int opt = (int) optionPane.getValue();
if(opt == JOptionPane.OK_OPTION) {
System.out.println("Ok then!");
} else {
System.out.println("Didn't think so.");
}
Upvotes: 1
Reputation: 347184
Ask described in the JavaDocs...
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;
You should be able to use JOptionPane#getValue()
However, unless you some massively pressing reason to do so, you should use one of the static
factory methods. See How to Make Dialogs for more details
Upvotes: 0
Reputation: 1051
Usually it can be done like this:
int response = JOptionPane.showConfirmDialog(parent, "message", "title", JOptionPane.OK_CANCEL_OPTION);
System.out.println(response);
Upvotes: 0