我有用于为我的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) {
}
}
当未选择任何行时,如何使“删除”按钮不起作用?喜欢要求用户在删除前选择一行吗?还消除了计算负数之和的可能性。谢谢
if (e.getSource() == movebutton) {
try {
int index[] = productTable.getSelectedRows();
Object[] row = new Object[4];
for (int i = 0; i < index.length; i++) {
row[0] = model.getValueAt(index[i], 0);
row[1] = model.getValueAt(index[i], 1);
row[2] = model.getValueAt(index[i], 2);
model2.addRow(row);
}
DefaultTableModel t = (DefaultTableModel) productTable.getModel();
int selectedRow = productTable.getSelectedRow();
{
total += Double.parseDouble(t.getValueAt(selectedRow, 2).toString());
}
cartAmount.setText("Total: P " + Double.toString(total));
}catch (ArrayIndexOutOfBoundsException a) {
}
}
[删除按钮:
if (e.getSource() == remove) {
try {
DefaultTableModel t = (DefaultTableModel) cartTable.getModel();
int getSelectedRowForDeletion = cartTable.getSelectedRow();
if (getSelectedRowForDeletion >= 0) {
int selectedRow = cartTable.getSelectedRow();
total -= Double.parseDouble(t.getValueAt(selectedRow, 2).toString());
cartAmount.setText("Total: P " + Double.toString(total));
model2.removeRow(getSelectedRowForDeletion);
JOptionPane.showMessageDialog(null, "Item removed from cart!");
} else {
JOptionPane.showMessageDialog(null, "Select an item to remove.");
}
} catch (ArrayIndexOutOfBoundsException a) {
}
}
我在添加值时删除了for循环,因为它将仅添加productTable中的下一项。删除按钮也是如此。