2

所以这是我第一次使用 JOptionPane,我想知道是否有人可以帮助解释我如何让我的两个按钮执行某些操作?出于所有意图和目的,只需打印出“嗨”。这是我的代码。到目前为止,如果我单击“Uhh ....”按钮,它只会打印出“Hi”,但我希望它在单击“w00t!!”时也能这样做。按钮。我知道它与参数“JOptionPane.YES_NO_OPTION”有关,但我不确定我到底要做什么。我在这里先向您的帮助表示感谢!

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

3 回答 3

4

javadocs

当 showXxxDialog 方法之一返回整数时,可能的值为:

YES_OPTION
NO_OPTION
CANCEL_OPTION
OK_OPTION
CLOSED_OPTION

所以,你的代码应该看起来像,

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

但无论如何,这个逻辑有点奇怪,所以我可能会推出我自己的对话。

于 2012-11-28T19:07:38.767 回答
0

在 JOPtionPane 类中有一些常量表示按钮的值。

 /** 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;

您更改了按钮的名称,因此,您的第一个按钮“Uhh”的值为 0,其按钮为“w00t!” 假定值为 1。

所以,你可以使用这个:

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

或者可能更好地使用 swicht/case 函数:

    switch (selection )
    {
        case 0:
        {

            break;
        }
        case 1:
        {

            break;
        }
        default:
        {
            break;
        }
    }
于 2012-11-28T19:11:42.593 回答
-3
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");
}
于 2012-11-28T19:09:18.123 回答