如何绑定两个不同的javafx属性:字符串和double(使用StringConverter)



对于此代码(javafx)。

StringProperty sp;
DoubleProperty dp;
StringConverter<Double> converter = new DoubleStringConverter();    
Bindings.bindBidirectional(sp, dp, converter);

我得到汇编错误(在Eclipse IDE中)

这是方法签名:

public static <T> void bindBidirectional(Property<String> stringProperty, Property<T> otherProperty, StringConverter<T> converter)

但是,如果我删除了(字符串converter)的参数化,那么我只会得到警告和代码。

StringConverter converter = new DoubleStringConverter();    

我试图避免使用原始类型的仿制药,因此我不必抑制IDE中的警告。

所以问题是:
编写此代码的正确模式是什么?

这可能是Javafx属性中的一个小"陷阱"。如果您仔细观察签名:

static <T> void bindBidirectional(Property<java.lang.String> stringProperty,
    Property<T> otherProperty, StringConverter<T> converter)

转换器的参数必须匹配属性的参数。但是(这里的惊喜)DoubleProperty实现了Property<Number>,因此在bindBidirectional中的不匹配。幸运的是,解决方案很简单:使用NumberStringConverter

StringProperty sp = ...;
DoubleProperty dp = ...;
StringConverter<Number> converter = new NumberStringConverter();
Bindings.bindBidirectional(sp, dp, converter);

您将获得可以指定转换格式的额外好处。

这是我解决方案的答案:

    ArrayList<Pair<Slider,Label>> sliderList = new ArrayList<Pair<Slider,Label>>(
            Arrays.asList(
                    new Pair<Slider,Label>(soundSlider, soundLabel),
                    new Pair<Slider,Label>(videoSlider, videoLabel),
    sliderList.forEach(p->{
        Bindings.bindBidirectional(p.getValue().textProperty(), p.getKey().valueProperty(), new NumberStringConverter() {
            @Override
            public String toString(Number value) {
                return super.toString(Math.round((double) value));
            }
        }); 
    });

最新更新