You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NetBeans JFrame中如何统计所有已选中CheckBox对应价格的总和

问题根因

你当前代码只能统计单个选中复选框金额的核心原因有两个:

  1. 使用else if做分支判断,只要第一个满足的条件命中后,后续所有分支都会直接跳过,不会执行
  2. 卡布奇诺的统计逻辑是直接给Total变量赋值,就算后续分支执行,也会被这一步的赋值覆盖结果

修复代码

将所有else if改为独立的if判断,同时把卡布奇诺的赋值改为累加逻辑即可:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    double total = 0.0;
              
    if(cbCappuccino.isSelected()){
        String cappucino = chboxCappucino.getValue().toString();
        int count1 = Integer.parseInt(cappucino);
        total += count1 * 1.0;
    }
    if(cbAmericano.isSelected()){
        String americano = chboxAmericano.getValue().toString();
        int count2 = Integer.parseInt(americano);
        total += count2 * 1.50;
    }
    if(cbLatte.isSelected()){
        String latte = chboxLatte.getValue().toString();
        int count3 = Integer.parseInt(latte);
        total += count3 * 2.50;
    } 
                
    totalText.setText(Double.toString(total));
}

可选优化方案

如果后续要新增更多饮品品类,可以把复选框、对应数值选择器、单价存入Map,循环遍历统计,避免写大量重复的if判断:

// 初始化映射关系,可放在类成员变量位置
Map<JCheckBox, Object[]> drinkConfig = new HashMap<>();
drinkConfig.put(cbCappuccino, new Object[]{chboxCappucino, 1.0});
drinkConfig.put(cbAmericano, new Object[]{chboxAmericano, 1.5});
drinkConfig.put(cbLatte, new Object[]{chboxLatte, 2.5});

// 统计逻辑
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    double total = 0.0;
    for (Map.Entry<JCheckBox, Object[]> entry : drinkConfig.entrySet()) {
        JCheckBox checkBox = entry.getKey();
        if (checkBox.isSelected()) {
            JSpinner spinner = (JSpinner) entry.getValue()[0];
            double price = (double) entry.getValue()[1];
            int count = Integer.parseInt(spinner.getValue().toString());
            total += count * price;
        }
    }
    totalText.setText(Double.toString(total));
}

你提供的运行截图参考:
当前仅能统计卡布奇诺的价格

内容的提问来源于stack exchange,提问作者Feliks_JS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 23:06:03