Use the cellValueFactory
as you have it to determine the data that is displayed. The cell value factory is basically a function that takes a CellDataFeatures
object and returns an ObservableValue
wrapping up the value to be displayed in the table cell. You usually want to call getValue()
on the CellDataFeatures
object to get the value for the row, and then retrieve a property from it, exactly as you do in your posted code.
Use a cellFactory
to determine how to display those data. The cellFactory
is a function that takes a TableColumn
(which you usually don't need) and returns a TableCell
object. Typically you return a subclass of TableCell
that override the updateItem()
method to set the text (and sometimes the graphic) for the cell, based on the new value it is displaying. In your case you get the price as a Number
, and just need to format it as you require and pass the formatted value to the cell's setText(...)
method.
It's worth reading the relevant Javadocs: TableColumn.cellFactoryProperty()
, and also Cell
for a general discussion of cells and cell factories.
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()));
}
}
});
(I'm assuming priceProductColumn
is a TableColumn<Product, Number>
and Product.priceProperty()
returns a DoubleProperty
.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…