Reputation: 19
I'm trying to make a POS system right now. I want to make my JTable add existing items to the same row while adjusting their quantity price.
For example: Product 1 already exists in the table and I want to add the same Product 1 but with different quantity. That additional product 1 will add its quantity to the previous Product 1 already in the table and then adjust the price of the product 1.
Hope I made myself clear.
Upvotes: 0
Views: 768
Reputation: 3103
Based on my understanding of your question and what's there in the comment. I think you basically need to manipulate the data in the JTable using the table model. (Oracle's tutorial on Jtable) Logic would be
When use click button to add product and quantity, you should find out whether the product has been in the table or not
model.getValueAt(i, PRODUCT_COL) != null && model.getValueAt(i, PRODUCT_COL).equals(product)
If the product has been added, find out the original quantity and add the new quantity to the original quanity
int orignialQuantity = Integer.parseInt(model.getValueAt(existingProductRowIndex, QUANTITY_COL).toString()); model.setValueAt(orignialQuantity + quantity, existingProductRowIndex, QUANTITY_COL);
Otherwise, insert a new row for the new product
model.addRow(new Object[]{product, quantity});
Running example:
public class POS extends JFrame {
String[] columns = {"Product", "Quantity"};
private final static int PRODUCT_COL = 0;
private final static int QUANTITY_COL = 1;
TableModel tableModel = new DefaultTableModel(columns, 0);
JTable table = new JTable(tableModel);
JComboBox comboBox = new JComboBox(new String[]{"Apple", "Banana"});
JTextField quantityJtf = new JTextField(10);
JButton jButton = new JButton("Add");
POS() {
this.setLayout(new FlowLayout());
this.add(new JScrollPane(table));
this.add(comboBox);
this.add(quantityJtf);
this.add(jButton);
jButton.addActionListener(new MyActionListener());
}
private class MyActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String product = comboBox.getSelectedItem().toString();
int quantity = Integer.parseInt(quantityJtf.getText().trim());
DefaultTableModel model = (DefaultTableModel) table.getModel();
int rowCount = model.getRowCount();
int existingProductRowIndex = -1;
for (int i = 0; i < rowCount; ++i) {
if (model.getValueAt(i, PRODUCT_COL) != null && model.getValueAt(i, PRODUCT_COL).equals(product)) {
existingProductRowIndex = i;
break;
}
}
if (existingProductRowIndex > -1) {
int orignialQuantity = Integer.parseInt(model.getValueAt(existingProductRowIndex, QUANTITY_COL).toString());
model.setValueAt(orignialQuantity + quantity, existingProductRowIndex, QUANTITY_COL);
} else {
model.addRow(new Object[]{product, quantity});
}
}
Upvotes: 0