[英]javafx: How can I format a double property for binding?
I have two double properties price1
and price2
. 我有两个双性
price1
和price2
。 I know that I can bind it to a label like this: 我知道我可以将其绑定到这样的标签上:
Locale locale = new Locale("en", "UK");
fxLabel.textProperty().bind(Bindings.format("price1/price2: %.3f/%.3f",.price1Property(),price2Property()));
but the displayed number does not have any commas separators (ie 123456.789 is shown instead of 123,456.789). 但显示的数字没有任何逗号分隔符(即显示的是123456.789,而不是123,456.789)。 Ideally, I would like to be do something like the following:
理想情况下,我希望执行以下操作:
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
But I have no idea how to do this on a property. 但是我不知道如何在一个属性上执行此操作。 How can I solve this ?
我该如何解决?
Using the JavaFX high level binding API, you can change the format string and pass the locale to Binding.format
: 使用JavaFX高级绑定API,您可以更改格式字符串,并将语言环境传递给
Binding.format
:
Locale locale = new Locale("en", "UK");
fxLabel.textProperty().bind(Bindings.format(locale, "price1/price2: %,.3f/%,.3f", price1Property(), price2Property()));
In this example, the ',' flag is used in the format string (all options and possibilities documented in the java.util.Formatter API doc . 在此示例中,格式字符串中使用了','标志( java.util.Formatter API doc中记录的所有选项和可能性)。
You can also use the low level binding API: 您还可以使用低级绑定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.