获取一些JCheckBox的索引

时间:2017-04-12 03:16:19

标签: java swing jcheckbox

我已经研究过,但是在这段代码中还没有进一步研究。 我正在构建一个GUI披萨计算器,它将大小和外壳(单选按钮)与选择了多少浇头(复选框)相加并检索最终值。

我创建了复选框数组和for循环:

        String[] toppings = {"Chicken", "Sausage", "Schrimp", "Mushroom", "Green pepper", "Tomatoe", "Onion", "Spinach", "Cheddar", "Mozzarela"};
            JCheckBox[] checkBoxes1 = new JCheckBox[toppings.length];
            for (int i = 0; i < checkBoxes1.length; i++) {
                checkBoxes1[i] = new JCheckBox(toppings[i]);
                checkBoxes1[i].setActionCommand(toppings[i]);
                p4.add(checkBoxes1[i]);
            }   

-P4是复选框所在的面板 -

然后我有另一个函数来返回该值并用JOption弹出总值。

public void finalPrice(){

    double sizeP = 0;
    double crustP = 0;
    double topP = 0;
    double totalP = 0;

    ButtonModel model1 = bg1.getSelection();
    String selec1 = (model1 == null) ? "" : model1.getActionCommand();
    ButtonModel model2 = bg2.getSelection();
    String selec2 = (model2 == null) ? "" : model2.getActionCommand();
    System.out.println(selec1 + " " + selec2);

    switch (selec1) {
    case "Small":
        sizeP = 4.50;
        break;
    case "Medium":
        sizeP = 7;
        break;
    case "Large":
        sizeP = 9;
        break;
    }

    switch (selec2) {
    case "Crunchy Thin Crust":
        crustP = 1;
        break;
    case "Hand Tossed Thin":
        crustP = 1.5;
        break;
    case "Medium Crust":
        crustP = 1.75;
        break;
    case "Homemade Pan":
        crustP = 2;
        break;
    }


    totalP = sizeP + crustP + topP;

    JOptionPane.showMessageDialog(null, 
            "Pizza Size: $" + sizeP +
            "\nPizza Crust: $" + crustP +
            "\nPizza Toppings: $" + topP +
            "\nTotal Price: $" + totalP
            );

}

我尝试使用JLists然后获取索引,但它没有成功。

可运行的例子:

http://collabedit.com/bq2nj

有什么想法吗?

提前谢谢!

1 个答案:

答案 0 :(得分:0)

对于那些和我有同样问题的人,我创建了一个简单的for循环

        index = 0;

    for (int i = 0; i < checkBoxes1.length; i++) {
        if(checkBoxes1[i].isSelected()){
            index += 1;
        }
    }

感谢您的帮助@MadProgrammer