[英]javafx: How can I format a double property for binding?
我有兩個雙性price1
和price2
。 我知道我可以將其綁定到這樣的標簽上:
Locale locale = new Locale("en", "UK");
fxLabel.textProperty().bind(Bindings.format("price1/price2: %.3f/%.3f",.price1Property(),price2Property()));
但顯示的數字沒有任何逗號分隔符(即顯示的是123456.789,而不是123,456.789)。 理想情況下,我希望執行以下操作:
String pattern = "###,###.###;-###,###.###";
DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(locale);
df.applyPattern(pattern);
df.setMinimumFractionDigits(3);
df.setMaximumFractionDigits(10);
// bind df.format(value from price1 and price 2 property) to the label
但是我不知道如何在一個屬性上執行此操作。 我該如何解決?
使用JavaFX高級綁定API,您可以更改格式字符串,並將語言環境傳遞給Binding.format
:
Locale locale = new Locale("en", "UK");
fxLabel.textProperty().bind(Bindings.format(locale, "price1/price2: %,.3f/%,.3f", price1Property(), price2Property()));
在此示例中,格式字符串中使用了','標志( java.util.Formatter API doc中記錄的所有選項和可能性)。
您還可以使用低級綁定API:
StringBinding stringBinding = new StringBinding() {
private final static Locale LOCALE = new Locale("en", "UK");
private final static DecimalFormat DF;
static {
String pattern = "###,###.###;-###,###.###";
DF = (DecimalFormat) NumberFormat.getNumberInstance(LOCALE);
DF.applyPattern(pattern);
DF.setMinimumFractionDigits(3);
DF.setMaximumFractionDigits(10);
}
public StringBinding() {
super.bind(price1Property(), price2Property());
}
@Override
protected String computeValue() {
return "price1/price2 " + DF.format(price1Property().get()) + "/" + DF.format(price2Property().get());
}
};
fxLabel.bind(stringBinding);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.