JavaFx在表列上使用String with Double

我有一个名为“Product”的类,具有双重属性“price”。 我在表格视图中的表格列上显示它,但我想显示格式化的价格 – “US $ 20.00”而不仅仅是“20.00”。

这是填充表视图的代码:

priceProductColumn.setCellValueFactory(cellData -> cellData.getValue().priceProperty()); 

我尝试了一切:将返回的值转换为字符串,使用priceProperty具有的方法toString等,但似乎不起作用。

我是否需要绑定类似的事件?

使用cellValueFactory来确定显示的数据。 单元格值工厂基本上是一个函数,它接受一个CellDataFeatures对象并返回一个ObservableValue ,它包含要在表格单元格中显示的值。 您通常希望在CellDataFeatures对象上调用getValue()来获取行的值,然后从中检索属性,就像在发布的代码中一样。

使用cellFactory确定如何显示这些数据。 cellFactory是一个函数,它接受一个TableColumn (你通常不需要)并返回一个TableCell对象。 通常,您返回一个TableCell的子类,它覆盖updateItem()方法,根据它显示的新值设置单元格的文本(有时是图形)。 在您的情况下,您将价格作为Number ,只需要根据需要格式化,并将格式化的值传递给单元格的setText(...)方法。

值得一读的是相关的Javadocs: TableColumn.cellFactoryProperty() ,还有Cell用于细胞和细胞工厂的一般性讨论。

 priceProductColumn.setCellValueFactory(cellData -> cellData.getValue().priceProperty()); priceProductColumn.setCellFactory(col -> new TableCell() { @Override public void updateItem(Number price, boolean empty) { super.updateItem(price, empty); if (empty) { setText(null); } else { setText(String.format("US$%.2f", price.doubleValue())); } } }); 

(我假设priceProductColumnTableColumnProduct.priceProperty()返回DoubleProperty 。)

如果还没有,请与@James_D一起阅读。

https://docs.oracle.com/javafx/2/ui_controls/table-view.htm