首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >添加重复项时,如何更新TableView中的行(而不是添加新行)?[JavaFX]

添加重复项时,如何更新TableView中的行(而不是添加新行)?[JavaFX]
EN

Stack Overflow用户
提问于 2016-12-10 20:58:55
回答 1查看 184关注 0票数 1

当您将一个项添加到一个ObservableList中,该项显示在一个TableView中时,当添加了一个重复的项时,如何更新一个行?

例如,假设TableView有三栏:商品、数量和价格。这可以通过以下代码来实现:

代码语言:javascript
复制
@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);
}

在其当前形式中,您可能会得到这样一个表:

项目

周民--1

垫泰式-1-1

周民--1

垫泰式-1-1

但我要找的是这样一张桌子:

项目

周民--1

泰垫-1-1

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-10 22:45:07

扫描表中的项,以查看是否存在现有项:

代码语言:javascript
复制
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);


}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41080272

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档