Bind TextField to ReadOnlyDoubleProperty

久未见 提交于 2020-12-08 07:39:13

问题


I can bind a TextField's text property to a DoubleProperty, like this:

textField.textProperty().bindBidirectional(someDoubleProperty, new NumberStringConverter());

But what if my someDoubleProperty is an instance of ReadOnlyDoubleProperty instead of DoubleProperty?

I am acutally not interested in a bidirectional binding. I use this method only because there is no such thing as

textField.textProperty().bind(someDoubleProperty, new NumberStringConverter());

Do I need to use listeners instead or is there a "binding-solution" for that as well?

Is there somthing like

textField.textProperty().bind(someDoubleProperty, new NumberStringConverter());

out there?


回答1:


For a unidirectional binding, you can do:

textField.textProperty().bind(Bindings.createStringBinding(
    () -> Double.toString(someDoubleProperty.get()),
    someDoubleProperty));

The first argument is a function generating the string you want. You could use a formatter of your choosing there if you wanted.

The second (and any subsequent) argument(s) are properties to which to bind; i.e. if any of those properties change, the binding will be invalidated (i.e. needs to be recomputed).

Equivalently, you can do

textField.textProperty().bind(new StringBinding() {
    {
        bind(someDoubleProperty);
    }

    @Override
    protected String computeValue() {
        return Double.toString(someDoubleProperty.get());
    }
});



回答2:


There is an another form of a simple unidirectional binding:

textField.textProperty().bind(someDoubleProperty.asString());


来源:https://stackoverflow.com/questions/48580397/bind-textfield-to-readonlydoubleproperty

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!