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.
相关文章