問題描述
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 格式加倍的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!