Bidirectional bindings of different properties

↘锁芯ラ 提交于 2019-11-29 07:25:38

Simple matter of type confusion

Bindings.bindBidirectional(textProp, intProp, new IntegerStringConverter());

Should be:

Bindings.bindBidirectional(textProp, intProp, new NumberStringConverter());

I tried your code in Eclipse and had to cast the converter. Then everything looks ok:

public class BiderectionalBinding {

    public static void main(String[] args) {
        SimpleIntegerProperty intProp = new SimpleIntegerProperty();
        SimpleStringProperty textProp = new SimpleStringProperty();
        StringConverter<? extends Number> converter =  new IntegerStringConverter();

        Bindings.bindBidirectional(textProp, intProp,  (StringConverter<Number>)converter);

        intProp.set(2);
        System.out.println(textProp);

        textProp.set("8");
        System.out.println(intProp);    
    }
}

The output is:

StringProperty [value: 2]

IntegerProperty [value: 8]

i had a similar problem. I tried to convert a string into a File-Object and back. But i used Bindings.bindBidirectional(...,...,java.text.Format). The conversion from the string to file worked as expected but in the other direction the result was null. I tried it with your example, same Result! I think there is a bug in the binding mechanism, or maybe my implementation of java.text.Format is wrong..

package de.ludwig.binding.model;

import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;

import javafx.beans.binding.Bindings;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;

public class BidirectionalBinding {

    public static void main(String[] args) {
        SimpleIntegerProperty intProp = new SimpleIntegerProperty();
        SimpleStringProperty textProp = new SimpleStringProperty();

        Bindings.bindBidirectional(textProp, intProp, new Format() {

            @Override
            public StringBuffer format(Object obj, StringBuffer toAppendTo,
                    FieldPosition pos) {
                return toAppendTo.append(obj.toString());
            }

            @Override
            public Object parseObject(String source, ParsePosition pos) {
                return Integer.parseInt(source);
            }

        });

        intProp.set(2);
        System.out.println(textProp);

        textProp.set("8");
        System.out.println(intProp);    
    }
}

The only way to get things working as expected was to implement StringConverter as recommended by Hendrik Ebbers. Thank you for this tip!

I think that is a bug. Anyway you can workaround like:

StringConverter sc = new IntegerStringConverter();
Bindings.bindBidirectional(textProp, intProp, sc);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!