Mike
Mike

Reputation: 1327

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

Upvotes: 2

Views: 2604

Answers (3)

user1329572
user1329572

Reputation: 6406

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.

Upvotes: 4

matheuslf
matheuslf

Reputation: 309

In JOPtionPane class there are some constants that represent the values ​​of the buttons.

 /** Return value from class method if YES is chosen. */
    public static final int         YES_OPTION = 0;
    /** Return value from class method if NO is chosen. */
    public static final int         NO_OPTION = 1;
    /** Return value from class method if CANCEL is chosen. */
    public static final int         CANCEL_OPTION = 2;

You changed the names of the buttons, and consequently, your first button "Uhh" has the value 0, and its button "w00t!" assumed a value of 1.

So, you can use this:

if(selection == JOptionPane.YES_OPTION)
{
    System.out.println("Hi");
}
else if(selection == JOptionPane.NO_OPTION){
    // do stuff
}

or maybe could be better use the swicht/case function:

    switch (selection )
    {
        case 0:
        {

            break;
        }
        case 1:
        {

            break;
        }
        default:
        {
            break;
        }
    }

Upvotes: 0

bhuang3
bhuang3

Reputation: 3633

int selection = 0;
JOptionPane.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");
}

Upvotes: -3

Related Questions