Search code examples
javaswingactionlistenerjoptionpanejdialog

Custom JDialog - Find out if OK was presed


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.


Solution

  • 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.");
    }