【问题标题】:How do you update a row (rather than add a new row) in a TableView when duplicate items are added? [JavaFX] [duplicate]添加重复项时,如何在 TableView 中更新一行(而不是添加新行)? [JavaFX] [重复]
【发布时间】:2016-12-10 20:58:55
【问题描述】:

当你向 ObservableList 添加一个 item 时,它正在一个 TableView 中显示,如果添加了重复的 item,你如何更新一行?

例如考虑一个包含三列的 TableView:项目、数量和价格。这可以通过以下代码实现:

@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);
}

在当前形式下,您最终可能会得到这样的表格:

item --------- 数量 ----- 价格 .
炒面 ----- 1 ------------ 4.20 .
泰语 -------- 1 ------------ 5.50 .
炒面 ----- 1 ------------ 4.20 .
泰语 -------- 1 ------------ 5.50。

但我要找的是这样的表格:

item --------- 数量 ----- 价格 .
炒面 ----- 1 ------------ 8.40 .
泰语 -------- 1 ---------- 11.00。

【问题讨论】:

    标签: java javafx collections tableview observablelist


    【解决方案1】:

    扫描表格的项目以查看是否存在现有项目:

    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);
    
    
    }
    

    【讨论】:

    • 这很棒。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2020-02-07
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-01
    • 2023-04-07
    相关资源
    最近更新 更多