java如何将TableView中TableColumn的和绑定到外部标签textProperty()?
有一个订单表视图,其中有一列用于表示订单成本。订单对象的成本属性可以在TableView中更改。这意味着Order列单元格可以使用TextFieldTableCell进行更改。此外,TableView之外还有一个标签,它应该表示订单成本的总和。现在,问题是我不知道如何将order costs列的总和绑定到Label的text属性()
下面是一些代码来澄清问题:
class Order {
private SimpleStringProperty name;
private SimpleIntegerProperty cost;
public String getName() {
return this.name.get();
}
public void setName(String name) {
this.name.set(name);
}
public SimpleStringProperty nameProperty() {
return this.name;
}
public Integer getCost() {
return this.cost.get();
}
public void setCost(Integer cost) {
this.cost.set(cost);
}
public SimpleIntegerProperty costProperty() {
return this.cost;
}
}
TableView<Order> tableView = new TableView<>();
TableColumn<Order, String> nameColumn = new TableColumn<>();
nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
nameColumn.setCellFactory(TextFieldTableCell.forTableColumn());
TableColumn<Order, String> costColumn = new TableColumn<>();
costColumn.setCellValueFactory(new PropertyValueFactory<>("cost"));
costColumn.setCellFactory(TextFieldTableCell.forTableColumn());
tableView.getColumns().addAll(nameColumn, costColumn);
Label totalCostLabel = new Label("Total cost should be updated in this label");
VBox vBox = new VBox();
vBox.getChildren().addAll(tableView, totalCostLabel);
# 1 楼答案
您可以执行以下操作:
创建一个} 映射到
ObservableList
和^{costProperty()
,并将其用作表的items
列表:这确保了当列表中的
costProperty
个元素发生更改时,列表会触发更新事件(除了在列表中添加或删除元素时触发的常规事件,等等)创建一个绑定到列表的
DoubleBinding
,并计算总成本:将标签的
textProperty()
绑定到总成本:如果您希望对}
asString()
方法的显示方式有更多的控制,那么可以向该方法提供^{以下是根据您的代码改编的完整示例: