Search code examples
javaswingjoptionpane

Java Swing JOptionPane Button Options


So this is my first time working with the JOptionPane and I was wondering if someone could help explain how I could make both of my buttons do certain actions? For all intent and purposes have it just print out "Hi". Here is my code. So far it only prints out "Hi" if I click the "Uhh...." button but I want it to do the same when I click the "w00t!!" button as well. I know it has something to do with the parameter "JOptionPane.YES_NO_OPTION" but I'm not sure what exactly I have to do with it. Thanks for the help in advance!

Object[] options = {"Uhh....", "w00t!!"};
int selection = winnerPopup.showOptionDialog(null,
    "You got within 8 steps of the goal! You win!!",
    "Congratulations!", JOptionPane.YES_NO_OPTION,
    JOptionPane.INFORMATION_MESSAGE, null,
    options, options[0]);
    if(selection == JOptionPane.YES_NO_OPTION)
    {
        System.out.println("Hi");
    }

Solution

  • From the javadocs,

    When one of the showXxxDialog methods returns an integer, the possible values are:

    YES_OPTION
    NO_OPTION
    CANCEL_OPTION
    OK_OPTION
    CLOSED_OPTION
    

    So, your code should look something like,

    if(selection == JOptionPane.YES_OPTION){
        System.out.println("Hi");
    }
    else if(selection == JOptionPane.NO_OPTION){
        System.out.println("wOOt!!");
    }
    

    But regardless, this logic is a bit bizarre so I would probably just roll my own dialog.