javafx中的细胞工厂 [英] Cell factory in javafx
问题描述
我使用的是 JavaFx 2.0 和 Java 7.问题是关于 JavaFX 中的表视图.
I am using JavaFx 2.0 and Java 7. The question is regarding Table View in JavaFX.
下面的示例代码创建一个 firstName 列并为其分配单元工厂和单元值工厂.
The below sample code creates a firstName column and assigns cell factory and cell value factory to it.
Callback<TableColumn, TableCell> cellFactory =
new Callback<TableColumn, TableCell>() {
public TableCell call(TableColumn p) {
return new EditingCell();
} };
TableColumn firstNameCol = new TableColumn("First Name");
firstNameCol.setCellValueFactory(
new PropertyValueFactory<Person,String>("firstName")
);
firstNameCol.setCellFactory(cellFactory);
我的要求是我有一列不直接映射到 Person 对象中的单个属性,而是通过连接 Person 对象的一个或多个属性创建的自定义值.
My requirement is I have a column which doesn't directly map to a single attribute in Person object, but instead is a custom value created by concatenating one or more attributes of Person object.
考虑一个场景,我有一个名为 Full Name 的表列,它的值是 Prefix + Last Name + "," + First Name .
Consider a scenario where I have a table column named Full Name which will have values of Prefix + Last Name + "," + First Name .
1) 在这种情况下,您将如何编写单元格值工厂?
1) In this scenario, how will you write the cell value factory?
firstNameCol.setCellValueFactory(
new PropertyValueFactory<Person,String>(???????)
);
2) 你将如何编写细胞工厂?
2) how will you write cell factory?
在这种情况下,我们需要同时实现细胞值工厂和细胞工厂还是任何一个就足够了?如果一个就足够了,那么哪一个?
In this scenario do we need to implement both cell value factory and cell factory or any one is sufficient? If one is sufficient then which one?
谢谢
推荐答案
直截了当,
细胞值工厂 :它就像是该相关单元格的行项目的一部分的toString()".
细胞工厂:它是单元格项中单元格的渲染器.如果单元格项不是 Node
,则默认行为是 setText(cell.item.toString()),否则为 setGraphic((Node)cell.item).如果单元格应该支持编辑,或者如果您想要除默认 Label
之外的更多图形(控件),请设置此属性.
Cell Value Factory : it is like a "toString()" of only part of the row item for that related cell.
Cell Factory : it is a renderer of the cell from the cell item. Default behavior is setText(cell.item.toString()) if the cell item is not a Node
, setGraphic((Node)cell.item) otherwise. Set this property if the cell is supposed to support editing OR if you want more graphics (controls) other than default Label
.
因此,对于您的场景,将单元工厂保留为默认值就足够了 (2).这是 (1) 的示例代码:
So for your scenario, leaving cell factory with default value will be sufficient (2). And here is sample code for (1):
firstAndLastNameCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Person, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(TableColumn.CellDataFeatures<Person, String> p) {
if (p.getValue() != null) {
return new SimpleStringProperty(p.getValue().getPrefix() + " " + p.getValue().getFirstName() + "," + p.getValue().getLastName());
} else {
return new SimpleStringProperty("<no name>");
}
}
});
这篇关于javafx中的细胞工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!