Home > Enterprise >  Incrementing a value in Java table doesn't work after one record
Incrementing a value in Java table doesn't work after one record

Time:09-18

While inserting row in data model table works fine for first record. If table empty insert a row if barcode=bcode_txt increment quantity. but after first record it doesn't work. It increments as well as creates a new row(duplicate). Below is code for review.

private void jBCodeKeyPressed(java.awt.event.KeyEvent evt) {

        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
            int numofrows = jTable1.getRowCount();
            if (numofrows == 0) {
                insert_row();
            }
            if (!(numofrows == 0)) {

                for (int i = 0; i < numofrows; i  ) {
                    int c_bcode = Integer.parseInt(model.getValueAt(i, 2).toString());
                    int bcode_txt = Integer.parseInt(jBCode.getText());
                    if (bcode_txt == c_bcode) {
                        int curr_qty = Integer.valueOf(model.getValueAt(i, 3).toString());
                        String entered_qty = p_qty.getText();
                        Double up = Double.parseDouble(p_u_price.getText());
                        int q = Integer.parseInt(entered_qty);
                        Double tp = q * up;
                        model.setValueAt(tp, i, 6);
                        q  = curr_qty;
                        model.setValueAt(q, i, 3);
                    } else if (!(bcode_txt == c_bcode) && (!(numofrows == 0))) {
                        insert_row();
                    }
                }
            }
        }
    }   

CodePudding user response:

I would iterate through all the rows first to find out if the bar code exists in the table. Once that is done then you check to see if you should update the existing row or insert a new row.

Your basic logic might be something like:

int barcodeRow = -1;
int bcode_txt = Integer.parseInt(jBCode.getText());

for (int i = 0; i < table.getRowCount(); i  )
{
    int c_bcode = Integer.parseInt(model.getValueAt(i, 2).toString());

    if (bcode_txt == c_bcode) 
    {
        barcodeRow = i;
        break;
    }
}

if (barcodeRow != -1)
    // update the row
else
    insertRow();

Also note you should not be adding a KeyListener to the text field. Instead, you can add an ActionListener. The ActionListener will be invoked when the Enter key is pressed.

  • Related