Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/396.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaFx使用表列上带双精度的字符串_Java_Javafx_Javafx 8 - Fatal编程技术网

JavaFx使用表列上带双精度的字符串

JavaFx使用表列上带双精度的字符串,java,javafx,javafx-8,Java,Javafx,Javafx 8,我有一个名为“Product”的类,具有双重属性“price”。我在表视图中的表列上显示它,但我想显示格式为“US$20.00”的价格,而不仅仅是“20.00” 以下是填充表视图的代码: priceProductColumn.setCellValueFactory(cellData -> cellData.getValue().priceProperty()); 我尝试了一切:使用priceProperty拥有的方法toString将返回值转换为字符串,等等,但似乎不起作用 我需要绑定这

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

以下是填充表视图的代码:

priceProductColumn.setCellValueFactory(cellData -> cellData.getValue().priceProperty());
我尝试了一切:使用priceProperty拥有的方法toString将返回值转换为字符串,等等,但似乎不起作用


我需要绑定这样的事件吗?

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

使用
cellFactory
确定如何显示这些数据。
cellFactory
是一个函数,它接受一个
TableColumn
(您通常不需要),并返回一个
TableCell
对象。通常,返回
TableCell
的子类,该子类重写
updateItem()
方法,根据单元格显示的新值设置单元格的文本(有时是图形)。在您的例子中,您将价格作为一个
数字
,只需根据需要对其进行格式化,并将格式化后的值传递给单元格的
setText(…)
方法

值得阅读相关的Javadocs:,以及关于细胞和细胞工厂的一般性讨论

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.setCellValueFactory(cellData->cellData.getValue().priceProperty());
priceProductColumn.setCellFactory(列->
新表单元格(){
@凌驾
public void updateItem(数字价格,布尔空){
super.updateItem(价格,空);
if(空){
setText(空);
}否则{
setText(String.format(“US$%.2f”,price.doubleValue());
}
}
});

(我假设
priceProductColumn
是一个
TableColumn
Product.priceProperty()
返回一个
DoubleProperty

如果没有,请与@James\u D post一起阅读


谢谢!!你能解释一下代码吗?我仍然是Java中的乞丐。基本上,他所做的是覆盖列的原始cellFactor。然后,如果价格为空,则文本不应为任何内容,如果价格不为空,则列文本应为价格。字符串格式在价格前加上美元。在此处阅读有关字符串格式的更多信息:使用说明更新。