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

如何避免向JTable中添加数据时出现重复数据

解决JTable添加数据重复的问题

你的代码核心问题是没有校验购物车中是否已存在同款商品,每次点击添加就直接新增行,导致重复数据。解决思路是:添加商品前先检查表格中是否已有相同Code的商品,存在则更新数量和小计,不存在再新增行。

修改后的代码实现

public void buyproduct() {
    String name = code_cart1.getText();
    try {
        con = Connector.getConnection();
        PreparedStatement pst = con.prepareStatement("SELECT `Code`, `Category`, `ProductName`, `Size`, `Quantity`, `Price`, `Sub-Total` FROM `product_table` WHERE Code = ?");
        pst.setString(1, name);
        rs = pst.executeQuery();
        while (rs.next()) {
            int currentqty = rs.getInt("Quantity");
            int pricenew = Integer.parseInt(price_cart1.getText());
            int qtynew = Integer.parseInt(quantity_cart1.getText());
            int tot = pricenew * qtynew;

            if (qtynew > currentqty || qtynew == 0) {
                JOptionPane.showMessageDialog(this, "Out of Stock!");
            } else {
                DefaultTableModel model = (DefaultTableModel) cart_Display.getModel();
                boolean productExists = false;
                // 遍历表格,检查是否已存在同款商品(通过Code判断)
                for (int i = 0; i < model.getRowCount(); i++) {
                    String existingCode = model.getValueAt(i, 0).toString();
                    if (existingCode.equals(name)) {
                        // 已存在,更新数量和小计
                        int existingQty = Integer.parseInt(model.getValueAt(i, 4).toString());
                        int newTotalQty = existingQty + qtynew;
                        int newSubTotal = pricenew * newTotalQty;
                        model.setValueAt(newTotalQty, i, 4);
                        model.setValueAt(newSubTotal, i, 6);
                        productExists = true;
                        break;
                    }
                }
                // 不存在则新增行
                if (!productExists) {
                    model.addRow(new Object[]{
                        code_cart1.getText(),
                        category_cart1.getText(),
                        productname_cart1.getText(),
                        size_cart1.getText(),
                        quantity_cart1.getText(),
                        price_cart1.getText(),
                        tot
                    });
                }
                // 重新计算总价
                int sum = 0;
                for (int i = 0; i < model.getRowCount(); i++) {
                    sum += Integer.parseInt(model.getValueAt(i, 6).toString());
                }
                SubTotal_Cart_text.setText(Integer.toString(sum));
                SubTotal_Cart_text1.setText(Integer.toString(sum));
                // 清空输入框
                code_cart1.setText("");
                category_cart1.setText("");
                productname_cart1.setText("");
                size_cart1.setText("");
                quantity_cart1.setText("");
                price_cart1.setText("");
            }
        }
    } catch(Exception ex) {
        ex.printStackTrace(); // 建议添加异常打印,方便排查问题
    }
}

额外优化建议

  • 计算总价时直接操作DefaultTableModel而非JTable,效率更高
  • 捕获异常时不要空处理,至少打印堆栈信息,便于排查潜在问题
  • 可以考虑将商品重复校验的逻辑抽成单独方法,让代码更清晰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 04:10:41