gpt4 book ai didi

java - 绑定(bind)到标签时格式化整数

转载 作者:行者123 更新时间:2023-12-02 02:18:11 25 4
gpt4 key购买 nike

我正在尝试格式化一个整数,同时将其绑定(bind)到标签的文本属性。

我知道我可以在值 setter 中使用 setText(),但我宁愿通过绑定(bind)以正确的方式进行操作。

在我的 Controller 初始化中,我有:

sec = new SimpleIntegerProperty(this,"seconds");
secondsLabel.textProperty().bind(Bindings.convert(sec));

但是当秒数低于 10 时,它显示为一位数,但我希望它保持两位数。所以我尝试将绑定(bind)更改为以下内容:

 secondsLabel.textProperty().bind(Bindings.createStringBinding(() -> {
NumberFormat formatter = NumberFormat.getIntegerInstance();
formatter.setMinimumIntegerDigits(2);
if(sec.getValue() == null) {
return "";
}else {
return formatter.format(sec.get());
}
}));

这将对其进行格式化,但是当我覆盖它时 sec.set(newNumber); 该值不会改变。

我也尝试过这个:

secondsLabel.textProperty().bind(Bindings.createStringBinding(() -> {
if(sec.getValue() == null) {
return "";
}else {
return String.format("%02d", sec.getValue());
}
}));

但这做了同样的事情。加载正常,显示两位数字,但是当通过 sec.set(newNumber); 更改数字时,没有任何变化。该数字永远不会高于 60 或低于零

最佳答案

您需要告诉您的绑定(bind),只要 sec 属性失效,它就应该失效。 Bindings.createStringBinding(...) 在函数后面接受一个 varargs 参数,该参数应该传递给绑定(bind)需要绑定(bind)的任何属性。您可以直接调整您的代码,如下所示:

secondsLabel.textProperty().bind(Bindings.createStringBinding(() -> {
NumberFormat formatter = NumberFormat.getIntegerInstance();
formatter.setMinimumIntegerDigits(2);
if(sec.getValue() == null) {
return "";
}else {
return formatter.format(sec.get());
}
}, sec));

secondsLabel.textProperty().bind(Bindings.createStringBinding(() -> {
if(sec.getValue() == null) {
return "";
}else {
return String.format("%02d", sec.getValue());
}
}, sec));

正如 @fabian 指出的,IntegerProperty.get() 永远不会返回 null,因此您可以删除 null 检查并执行以下操作:

secondsLabel.textProperty().bind(Bindings.createStringBinding(
() -> String.format("%02d", sec.getValue()),
sec));

绑定(bind) API 中有一个方便的版本:

secondsLabel.textProperty().bind(Bindings.format("%02d", sec));

关于java - 绑定(bind)到标签时格式化整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48950076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com