TableColumn中的JavaFX格式加倍

TableColumn中的JavaFX格式加倍

本文介绍了TableColumn中的JavaFX格式加倍的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TableColumn<Product, Double> priceCol = new TableColumn<Product,Double>("Price");
priceCol.setCellValueFactory(new PropertyValueFactory<Product, Double>("price"));

如何格式化此列中的双精度数以获得2位小数(因为它们是价格)?默认情况下,它们只显示1位小数。

How do I format the doubles in this column to have 2 decimal places(Because they are the column for price)?By default they only show 1 decimal place.

推荐答案

使用生成使用货币格式化程序的单元格的单元工厂格式化显示的文本。这意味着价格将被格式化为当前区域设置中的货币(即使用本地货币符号和小数位数的适当规则等)。

Use a cell factory that generates cells that use a currency formatter to format the text that is displayed. This means the price will be formatted as a currency in the current locale (i.e. using the local currency symbol and appropriate rules for number of decimal places, etc.).

NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
priceCol.setCellFactory(tc -> new TableCell<Product, Double>() {

    @Override
    protected void updateItem(Double price, boolean empty) {
        super.updateItem(price, empty);
        if (empty) {
            setText(null);
        } else {
            setText(currencyFormat.format(price));
        }
    }
});

注意除了 cellValueFactory之外,这是 您已经在使用。 cellValueFactory 确定单元格中显示的值; cellFactory 确定定义如何显示它的单元格。

Note this is in addition to the cellValueFactory you are already using. The cellValueFactory determines the value that is displayed in a cell; the cellFactory determines the cell that defines how to display it.

这篇关于TableColumn中的JavaFX格式加倍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 08:33