Home > Software engineering >  How to decrement the quantity in a specific row while clicking
How to decrement the quantity in a specific row while clicking

Time:06-30

I have a problem in my code while clicking the selected row the quantity reset to 1

I want to decrement it by 1 and also when the quantity hits the minimum value the selected row will be removed.

BTW I'm using AbstractTableModel to manage my data.

private void OrderListMouseClicked(java.awt.event.MouseEvent evt) {
    OrderTableModel model = (OrderTableModel) OrderList.getModel();
    Order order = new Order();
    int row = OrderList.getSelectedRow();
    int currentqty = (int) (model.getValueAt(row, 2));
    order =  model.getOrderAt(row);
    for (int i=currentqty - 1; i>=1; i--){
        currentqty = i;
    }
    order.setQuanity(currentqty);
    model.update(order);

screen capture

CodePudding user response:

In your click handler, you just need to decrement the value by one (instead of looping until it is 1) and if it hits the minimum we need to call a function to remove the row in the Model:

private void OrderListMouseClicked(java.awt.event.MouseEvent evt) {                                       
    OrderTableModel model = (OrderTableModel) OrderList.getModel();
    Order order = new Order();
    int row = OrderList.getSelectedRow();
    int currentqty = (int) (model.getValueAt(row, 2));
    
    order =  model.getOrderAt(row);
    // decrement current quantity by one
    currentqty--;
    // if current quantity has hit the minimum? - i assumed 0 would be the number where you want to remove the row
    if (currentqty <= 0) {
        model.removeRowAt(row);
    } else {
        order.setQuanity(currentqty);
        model.update(order);
    }
}

In your class OrderTableModel you have to add this function for the remove to work:

public void removeRowAt(int row) {
    filters.remove(row);
    fireTableRowsDeleted(row, row);
}

As these are only code snippets I was not able to run & test the code, but it should work.

  • Related