从JOptionPane返回值,表示所选按钮

时间:2013-02-21 13:13:54

标签: java switch-statement joptionpane

我已经制作了一个选项面板,但我无法让按钮实际按照它们的意图去做。 我试图将动作设为一个连接到面板的int,但这不起作用。

Object[] choices = null;
    Object[] options = { "Criticals", "Pure Damage", "Heal 300 points", "Flee" };
    JOptionPane.showOptionDialog(null, "What will you do?", "action",
            JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE,
            null, options, options[0]);

    switch (action)
    {
    case 0: 
        int Criticals = (int) (Math.random()*500);
        Criticals++;
        caitlyn.enemyhealth = (caitlyn.enemyhealth-Criticals);
        JOptionPane.showMessageDialog(null, "Caitlyn now has" +" " + caitlyn.enemyhealth + "HP left");
        break;
    case 1:
        int PureDamage = (int) (Math.random()*300);
        PureDamage++;
        caitlyn.enemyhealth = (caitlyn.enemyhealth-PureDamage);
        JOptionPane.showMessageDialog(null, "Caitlyn now has" + " " + caitlyn.enemyhealth + "HP left");
        break;
    case 2:
        int heal = 300;
        heal++;
        newchamp.health = (newchamp.health+heal);
        JOptionPane.showMessageDialog(null,  "You now have"+ " " + newchamp.health + "HP points!");
        break;

另外,我不知道如何做到这一点,以便已经完成的伤害或治疗被保存并将保持在下一次攻击的那个级别,而不是恢复到默认值。

1 个答案:

答案 0 :(得分:3)

我认为你需要:

    int action = JOptionPane.showOptionDialog(null, "What will you do?", "action",
        JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE,
        null, options, options[0]);

您忽略了方法的返回值,该值告诉您按下了哪个按钮。