Java 绑定到标签时格式化整数

Java 绑定到标签时格式化整数,java,user-interface,javafx,data-binding,number-formatting,Java,User Interface,Javafx,Data Binding,Number Formatting,我试图格式化一个整数,同时将其绑定到标签的text属性 我知道我可以在我的值setter中使用setText(),但我宁愿通过绑定以正确的方式使用它 在控制器初始化中,我有: sec = new SimpleIntegerProperty(this,"seconds"); secondsLabel.textProperty().bind(Bindings.convert(sec)); 但是当秒数降到10以下时,它显示为一个位数,但我希望它保持为两位数。因此,我尝试将绑定更改为以下内容: se

我试图格式化一个整数,同时将其绑定到标签的text属性

我知道我可以在我的值setter中使用setText(),但我宁愿通过绑定以正确的方式使用它

在控制器初始化中,我有:

sec = new SimpleIntegerProperty(this,"seconds");
secondsLabel.textProperty().bind(Bindings.convert(sec));
但是当秒数降到10以下时,它显示为一个位数,但我希望它保持为两位数。因此,我尝试将绑定更改为以下内容:

 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或低于零

您需要告诉您的绑定,它应该在
属性失效时失效<代码>绑定。createStringBinding(…)
在函数之后接受一个varargs参数,该参数应传递给绑定需要绑定的任何属性。您可以按如下方式直接调整代码:

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

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

secondsLabel.textProperty().bind(Bindings.createStringBinding(
    () -> String.format("%02d", sec.getValue()),
    sec));
绑定API中有一个方便的版本:

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

IntegerProperty继承了许多有用的方法,包括:


我只是试着把它放在它自己的例子中,但同样的事情发生了,这是有道理的,我只是试了一下,效果很好!感谢检查
null
是不必要的,因为使用了
IntegerProperty
,任何将值设置为
null
的尝试都会导致属性中的值变为
0
@fabian Yes:这是盲目从OP复制代码的结果。将该信息添加到答案中。
secondsLabel.textProperty().bind(Bindings.format("%02d", sec));
secondsLabel.textProperty().bind(sec.asString("%02d"));