【发布时间】:2020-04-10 11:04:25
【问题描述】:
我有为我的JTable 添加和删除单行的代码,但它会导致一些问题,例如在从JTable 中删除后无法准确计算总和和减法。 JTable 充当“购物车”,用于在购物车中添加和删除商品。
add to cart 用于向购物车添加行的按钮:
if (e.getSource() == movebutton) {
TableModel model1 = productTable.getModel();
int index[] = productTable.getSelectedRows();
Object[] row = new Object[4];
DefaultTableModel model2 = (DefaultTableModel) cartTable.getModel();
for (int i = 0; i < index.length; i++) {
row[0] = model1.getValueAt(index[i], 0);
row[1] = model1.getValueAt(index[i], 1);
row[2] = model1.getValueAt(index[i], 2);
model2.addRow(row);
getSum();
}
添加整体项目的代码:
public void getSum() { //column 02 is where the item's prices are listed
for (int i = 0; i < cartTable.getRowCount(); i++) {
total += Double.parseDouble(cartTable.getValueAt(i, 2).toString());
}
cartAmount.setText("Total: P " + Double.toString(total));
}
}
remove an item from the cart 按钮代码:
try {
for (int i = 0; i < cartTable.getRowCount(); i++) {
total = total - Double.parseDouble(cartTable.getValueAt(i, 2).toString());
}
cartAmount.setText("Total: P " + Double.toString(total));
if (total <= 0.0) {
total = 0.0;
}
{
int getSelectedRowForDeletion = cartTable.getSelectedRow();
model2.removeRow(getSelectedRowForDeletion);
JOptionPane.showMessageDialog(null, "Item removed from cart");
}
} catch (NumberFormatException ex) {
ex.printStackTrace();
} catch (ArrayIndexOutOfBoundsException ex) {
}
}
当没有选择行时,如何使删除按钮不起作用?比如要求用户在删除前选择一行?还消除了负和计算的可能性。谢谢
【问题讨论】:
-
JTables 的数据模型不应该是 TableModel。您应该将这些信息保存在普通的旧 Java 类中。 TableModel 将从数据模型中获取其信息。按钮的动作监听器是您进行计算的地方。
-
@GilbertLeBlanc 好的,我删除了 TableModel 并使用了 DefaultTableModel。另外,我删除了 getSum();并在添加到购物车按钮中插入计算。还是一样的结果:(
标签: java swing jtable add subtraction