Java Swing JOptionPane按钮选项

时间:2012-11-28 19:03:03

标签: java swing joptionpane

所以这是我第一次使用JOptionPane,我想知道是否有人可以帮助解释我是如何让我的两个按钮做某些动作的?出于所有意图和目的,它只打印出“嗨”。这是我的代码。到目前为止,如果我单击“呃......”按钮,它只打印出“嗨”,但是当我点击“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");
    }

3 个答案:

答案 0 :(得分: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!!");
}

但无论如何,这个逻辑有点奇怪,所以我可能只是滚动自己的对话框。

答案 1 :(得分: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;
        }
    }

答案 2 :(得分:-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");
}