简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM