JavaFX:如何将计算的整数值添加到TableColumn中
我有一张账单表,我想列出账单上的所有产品。账单上我保存了ProductInBill
对象内的ArrayList<ProductInBill>
。JavaFX:如何将计算的整数值添加到TableColumn中
当我创建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,而不是使用预制的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;
});
希望它帮助
!