[英]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.