1

When you add an item to an ObservableList, which is being displayed in a TableView, how can you update a row when a duplicate item is added?

e.g. Consider a TableView with three columns: item, quantity and price. This could be achieved with the following code:

@FXML
TableColumn itemColumn;
@FXML
TableColumn qtyColumn;
@FXML
TableColumn priceColumn;

TableView orderTable;
ObservableList orderList = FXCollections.observableArrayList();


public void addItem(String a, int b, Double c) {
    Item entry = new Item(a, b, c);
    currentOrderTable.getItems().add(entry);
}
@Override
public void initialize(URL location, ResourceBundle resources) {
    itemColumn.setCellValueFactory(new PropertyValueFactory<Item, Integer>("item"));
    qtyColumn.setCellValueFactory(new PropertyValueFactory<Item, String>("quantity"));
    priceColumn.setCellValueFactory(new PropertyValueFactory<Item, Double>("price"));
    orderTable.setItems(orderList);
}

In its current form, you could end up with a table like this:

item --------- quantity ----- price .
Chow Mein ----- 1 ----------- 4.20 .
Pad Thai -------- 1 ----------- 5.50 .
Chow Mein ----- 1 ----------- 4.20 .
Pad Thai -------- 1 ----------- 5.50.

But what I am looking for is a table like this:

item --------- quantity ----- price .
Chow Mein ----- 1 ----------- 8.40 .
Pad Thai -------- 1 ---------- 11.00 .

mrchimpbanana
  • 13
  • 1
  • 8

1 Answers1

0

Scan through the table's items to see if there is an existing item:

public void addItem(String itemName, int quantity, Double price) {

    Item entry = currentOrderTable.getItems().stream()
        .filter(item -> item.getItem().equals(itemName))
        .findAny()
        .orElseGet(()-> {
             Item newItem = new Item(itemName, 0, 0);
             currentOrderTable.getItems().add(newItem);
             return newItem ;
        });

    entry.setQuantity(entry.getQuantity() + quantity)
    entry.setPrice(entry.getPrice() + price);


}
James_D
  • 201,275
  • 16
  • 291
  • 322