Return Value from JOptionPane indicating the button selected

给你一囗甜甜゛ 提交于 2019-12-11 06:47:09

问题


I have made an option panel, but I can't get the buttons to actually do as they are meant to. I have tried to make action an int which is connected to the panel, but that doesn't work.

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;

also, I don't know how I would make it so that the damage or the heal that has been done, is saved and will stay at that level for the next attack, instead of return to default.


回答1:


I think you need:

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

You're ignoring the return value of the method, which tells you which button is pressed.



来源:https://stackoverflow.com/questions/15003170/return-value-from-joptionpane-indicating-the-button-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!