在TableView中显示DoubleProperty最多两个小数位

时间:2015-07-09 13:29:38

标签: java javafx

我遇到问题,直到第二个小数点才显示doubleProperty。

粗略的布局如下:

public static void main(String[] args) {
    private TableView<myType> myTable;
    private TableColumn<myType, Double> myCol;

public class myObject {
    .....
    DoubleProperty myDouble;
    ....

    public doubleProperty getPropertyMyDouble() {
        return myDouble;
    }

    public void setMyDouble(double d) {
        myDouble.set(d)
    }
}

我在列中填写:

   ...
   myCol.setCellValueFactory(cellData ->cellData.getValue().getPropertyMyDouble().asObject());
   ...

现在我的问题是这样的:如果我按照setMyDouble方式离开,myCol充满了数字 很多小数。我只想要小数点后两位。

我尝试做的是这样的:

public void setMyDouble(double d) {
        BigDecimal bd = new SimpleDecimalFormat("#.00")
        myDouble.set(Double.parseDouble(bd.format(d));
    }

现在这适用于删除第二个小数后的数字,但问题是如果我有东西 像12.00,因为我需要在最后转换为一个双精度(因为.set()需要一倍)它变成12.00 进入12.0。但是,我需要一直保留两位小数。

有没有办法让myDouble成为DoubleProperty(我这样做是因为它会让更改后的表自动更新) 但是以"#.##"格式显示数据?

我在考虑做一些像添加实例变量的事情:

StringProperty myDoublePresent;

只需myDouble并将其转换为字符串,然后以"#.##"格式显示。

但我更喜欢一种可以直接使用DoubleProperty.

的方法

2 个答案:

答案 0 :(得分:6)

尝试

myCol.setCellValueFactory(cellData ->
     Bindings.format("%.2f", cellData.getValue().getPropertyMyDouble()));

答案 1 :(得分:3)

遵循James_D在接受的答案中的建议是允许格式化任何列的通用解决方案。

public class DecimalColumnFactory<S, T extends Number> implements Callback<TableColumn<S, T>, TableCell<S, T>> {

    private DecimalFormat format;

    public DecimalColumnFactory(DecimalFormat format) {
        super();
        this.format = format;
    }

    @Override
    public TableCell<S, T> call(TableColumn<S, T> param) {
        return new TableCell<S, T>() {

            @Override
            protected void updateItem(T item, boolean empty) {
                if (!empty && item != null) {
                    setText(format.format(item.doubleValue()));
                } else {
                    setText("");
                }
            }
        };
    }
}

可以使用

theColumn.setCellFactory(new DecimalColumnFactory<>(new DecimalFormat("0.00")));
相关问题