带有两位小数的JavaFX浮点列

时间:2018-04-25 19:30:56

标签: sorting javafx tableview tablecolumn

我想在TableView中使用小数打印浮点数。但格式化浮动会破坏列的排序。

    TableColumn<Model, String> profit = new TableColumn<Model, String>("Profit");
    profit.setCellValueFactory(new PropertyValueFactory<Model, String>("profit"));
    profit.setCellValueFactory(cellData -> Bindings.format("%.2f", cellData.getValue().getProfit()));

enter image description here

如果我没有格式化列,则排序是正确的。但是表格每次都显示不是两位小数。

    TableColumn<Model, Float> profit = new TableColumn<Model, Float>("Profit");
    profit.setCellValueFactory(new PropertyValueFactory<Model, Float>("profit"));

enter image description here

1 个答案:

答案 0 :(得分:2)

使用单元格工厂确定单元格显示的数据,并使用单元工厂确定单元格应如何显示这些数据:

TableColumn<Model, Float> profit = new TableColumn<Model, Float>("Profit");
profit.setCellValueFactory(new PropertyValueFactory<Model, Float>("profit"));
profit.setCellFactory(tc -> new TableCell<Model, Float>() {
    @Override
    protected void updateItem(Float profit, boolean empty) {
        super.updateItem(profit, empty);
        if (empty) {
            setText(null);
        } else {
            setText(String.format("%.2f", profit.floatValue()));
        }
    }
});