I'm a newbie software developer, interested in Java desktop and web applications. I'm writing a desktop application, using only Swing components, which reads codes and, by retrieving the relative fields from a database, writes them in a JTable. I'm having troubles because the program adds a new row with the same code as many times as I enter the code, instead of increasing the quantity column of the already-entered code.
I want the program to perfom a check on the first column, by iterating the search on every row until it finds the code, if present, or reaches the last row. If it's a new code, a row must be added, instead if it's an already-entered code, the actual item quantity must be increased by one. Below comes my solution, not working, may you help? Thank you for the attention.
private void cmdFindItemActionPerformed(java.awt.event.ActionEvent evt) {
try {
item = Item.findItem(itemTextField.getText(), DeskApp.conn);
// Definition and initialisation of control variables pertaining "while" cycle
boolean isCodePresent = false;
int row = 0;
double discount = 0.0d;
double colSum = 0.0d;
// Discounted price = unit price * qty * (1 - discount)
while (!isCodePresent && row < defMod.getRowCount()) {
// Code already present: add quantity
if (item.getCode() == defMod.getValueAt(row, 0)) {
int actualQty = (int)defMod.getValueAt(row, 4);
defMod.setValueAt(++actualQty, row, 4);
double unitPrice = (double) defMod.getValueAt(row, 3);
discount = (double)defMod.getValueAt(row, 5);
double totRow = unitPrice * actualQty * (100 - discount) / 100;
defMod.setValueAt(totRow, row, 6);
double discountedPrice = (double)defMod.getValueAt(row, 3) *
(double)defMod.getValueAt(row, 4) *
((100 - (double)defMod.getValueAt(row, 5) / 100));
defMod.setValueAt(discountedPrice, row, 6);
isCodePresent = true;
}
row++;
}
// Code not yet present: add row
if (!isCodePresent) {
MyButton buttonAdd = new MyButton(MyButton.BEHAVIOUR_ADD, table.getRowCount());
MyButton buttonRemove = new MyButton(MyButton.BEHAVIOUR_REMOVE, table.getRowCount());
MyButton buttonDeleteRow = new MyButton(MyButton.BEHAVIOUR_DELETE_ROW, table.getRowCount());
buttonAdd.setText("+1");
buttonRemove.setText("-1");
buttonDeleteRow.setText("Delete row");
DecimalFormat digitFormat = new DecimalFormat("#.##");
for (int i = 0; i < defMod.getRowCount(); i++) {
colSum += (double) defMod.getValueAt(i, 6);
}
double discountedPrice = (double)defMod.getValueAt(row, 3) *
(double)defMod.getValueAt(row, 4) *
((100 - (double)defMod.getValueAt(row, 5) / 100));
defMod.addRow(new Object[]{item.getCode(), item.getOtherCode(),
item.getDescription(), item.getPrice(), 1, discount,
item.getPrice(), buttonAdd, buttonRemove, buttonDeleteRow});
}