JavaFx在表列上使用String with Double [英] JavaFx use String with Double on table column
问题描述
我有一个名为Product的类,具有双重属性price。我在表格视图中的表格列上显示它,但我想显示格式化的价格 - US $ 20.00而不是20.00。
I have a class called "Product", with a double attribute "price". I'm showing it on a table column inside a table view, but i wanted to show the price formatted -- "US$ 20.00" instead of just "20.00".
这是填充表格视图的代码:
Here's my code for populating the table view:
priceProductColumn.setCellValueFactory(cellData -> cellData.getValue().priceProperty());
我尝试了一切:将返回的值转换为字符串,使用priceProperty具有的方法toString等,但似乎不起作用。
I tried everything: convert the returned value to a string, using the method toString that priceProperty has, etc, but not seems to work.
我是否需要绑定类似的事件?
Do i need to bind an event of something like that?
推荐答案
使用 cellValueFactory
来确定显示的数据。单元格值工厂基本上是一个函数,它接受 CellDataFeatures
对象并返回 ObservableValue
包装要显示的值在表格单元格中。您通常希望在 CellDataFeatures
对象上调用 getValue()
来获取该行的值,然后检索它的属性,就像你发布的代码一样。
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.
使用 cellFactory
确定如何显示这些数据。 cellFactory
是一个函数,它接受 TableColumn
(你通常不需要)并返回 TableCell
对象。通常,您返回 TableCell
的子类,它覆盖 updateItem()
方法以设置文本(有时是图形)对于单元格,基于它显示的新值。在你的情况下,你得到的价格为数字
,只需要根据需要格式化它,并将格式化的值传递给单元格的 setText(。 ..)
方法。
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.
值得阅读相关的Javadocs: TableColumn.cellFactoryProperty()
,并且还 Cell
用于细胞和细胞工厂的一般性讨论。
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()));
}
}
});
(我假设 priceProductColumn
是一个 TableColumn< Product,Number>
和 Product.priceProperty()
返回 DoubleProperty
。)
(I'm assuming priceProductColumn
is a TableColumn<Product, Number>
and Product.priceProperty()
returns a DoubleProperty
.)
这篇关于JavaFx在表列上使用String with Double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!