我有一个名为“Product”的类,具有双属性“price”。我将其显示在 TableView 内的表列上,但我想显示格式为“US$ 20.00”的价格,而不仅仅是“20.00”。
这是我用于填充 TableView 的代码:
priceProductColumn.setCellValueFactory(cellData -> cellData.getValue().priceProperty());
我尝试了一切:将返回值转换为字符串,使用priceProperty具有的toString方法等,但似乎不起作用。
我需要绑定(bind)类似的事件吗?
最佳答案
使用cellValueFactory
因为您可以用它来确定显示的数据。单元值工厂基本上是一个采用 CellDataFeatures
的函数。对象并返回 ObservableValue
包装要在表格单元格中显示的值。您通常想调用getValue()
关于CellDataFeatures
对象来获取该行的值,然后从中检索属性,就像您在发布的代码中所做的那样。
使用 cellFactory
以确定如何显示这些数据。 cellFactory
是一个采用 TableColumn
的函数(您通常不需要)并返回 TableCell
目的。通常您返回 TableCell
的子类覆盖 updateItem()
方法根据单元格显示的新值设置单元格的文本(有时是图形)。在您的情况下,您得到的价格为 Number
,只需根据需要对其进行格式化并将格式化的值传递给单元格的 setText(...)
方法。
值得阅读相关的 Javadocs: TableColumn.cellFactoryProperty()
,还有 Cell
有关细胞和细胞工厂的一般讨论。
priceProductColumn.setCellValueFactory(cellData -> cellData.getValue().priceProperty());
priceProductColumn.setCellFactory(col ->
new TableCell<Product, Number>() {
@Override
public void updateItem(Number price, boolean empty) {
super.updateItem(price, empty);
if (empty) {
setText(null);
} else {
setText(String.format("US$%.2f", price.doubleValue()));
}
}
});
(我假设 priceProductColumn
是 TableColumn<Product, Number>
并且 Product.priceProperty()
返回 DoubleProperty
。)
关于JavaFx 在表列上使用 String 和 Double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27117949/