JavaFX:如何将计算的整数值添加到 TableColumn



我有一个账单表,我想在其中列出账单上的所有产品。我将ProductInBill对象保存在账单上的ArrayList<ProductInBill>内。

当我创建TableView时,我的常用方法是创建 JavaFX 字段。在控制器类上,我有我的字段:

@FXML public TableColumn<ProductInBill, String> finishedBillProductNameColumn;
@FXML public TableColumn<Integer, Integer> finishedBillProductNumberColumn;
@FXML public TableColumn<ProductInBill, Integer> finishedBillProductPriceBruttoLabel;
@FXML public TableColumn<Integer, Integer> finishedBillProductTotalAmountColumn;
@FXML public TableView finishedBillProductTable;

然后我使用一个setUp()方法,代码如下:

private void setUpFinishedBillProductTable() {
    finishedBillProductNameColumn.setCellValueFactory(new PropertyValueFactory<ProductInBill, String>("productName"));
    finishedBillProductPriceBruttoLabel.setCellValueFactory(new PropertyValueFactory<ProductInBill, Integer>("productPrice"));
}

还有一个updateBillTable()方法来加载必要的ProductInBill对象,将它们保存到 TableList 并将其提供给表。

 private void updateFinishedBillProductTable(Bill bill) {
    LOG.info("Start reading all Products from Bill");
    for(ProductInBill product : bill.getProducts()){
          finishedBillProductCurrent.add(product);
    }
    finishedBillProductTable.getItems().clear();

    if(!finishedBillProductCurrent.isEmpty()) {
        for (ProductInBill p : finishedBillProductCurrent) {
                finishedBillProductTableList.add(p);
        }
        //here i want to calculate some other Integer values based on the ProductInBill values and insert them to the table too.  
        finishedBillProductTable.setItems(finishedBillProductTableList);
    }
}

这一切都工作得很好。我现在的问题是,我的TableView上还有一个字段,其中包含计算的整数值,我不想将其保存在对象中。

finishedBillProductNumberColumn为例。我想迭代我的ArrayList,找到所有具有相同名称的产品并将相同项目的数量填充到表中。

我该怎么做?我只找到了必须使用对象中的值才能向TableView插入某些内容的解决方案。

你只需要为这些情况编写一个自定义的CellValueFactory,而不是使用预制的。使用PropertyValueFactory只是用成员填充单元格的便捷快捷方式。

对于您的示例:

 finishedBillProductNameColumn.setCellValueFactory(new PropertyValueFactory<ProductInBill, String>("productName"));

只是一个较短的方法:

finishedBillProductNameColumn.setCellValueFactory( cellData -> {
    ProductInBill productInBill = cellData.getValue();
    return data == null ? null : new SimpleStringProperty(productInBill.getProductName());
 });

话虽如此,我对第二种语法有 100% 的偏好。因为在第一个上,如果您重命名成员,并且您忘记在那里更改它,则直到您在应用程序中到达那里之前,您才会知道有错误。此外,它允许显示与成员不同的值。

作为您finishedBillProductNumberColumn的具体示例,您可以执行以下操作:

首先更改定义(第一个泛型类型是收到的带有cellData.getValue()的类型:

@FXML public TableColumn<ProductInBill, Integer> finishedBillProductNumberColumn;

然后定义您想要的 CellValueFactory,如下所示:

finishedBillProductNumberColumn.setCellValueFactory( cellData -> {
    ProductInBill productInBill = cellData.getValue();
    if(productionInBill != null){
        Long nbProduct = finishedBillProductTable.getItems().stream().filter(product -> product.getProductName().equals(productInBill.getProductName())).count();
        return new SimpleIntegerProperty(nbProduct.intValue()).asObject();
    }
    return null;
});

希望它有帮助!

最新更新