不同属性的双向绑定
我只是试图绑定一个Integer和一个String属性。 经过一些谷歌搜索后,应该可以使用以下两种方法之一:
-
public static void bindBidirectional(Property stringProperty,
属性otherProperty,StringConverter转换器) -
public static void bindBidirectional(Property stringProperty,
属性otherProperty,java.text.Format格式)
不幸的是,这似乎对我不起作用。 我究竟做错了什么?
import java.text.Format; import javafx.beans.binding.Bindings; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import javafx.util.converter.IntegerStringConverter; public class BiderectionalBinding { public static void main(String[] args) { SimpleIntegerProperty intProp = new SimpleIntegerProperty(); SimpleStringProperty textProp = new SimpleStringProperty(); Bindings.bindBidirectional(textProp, intProp, new IntegerStringConverter()); intProp.set(2); System.out.println(textProp); textProp.set("8"); System.out.println(intProp); } }
简单的类型混淆问题
Bindings.bindBidirectional(textProp, intProp, new IntegerStringConverter());
应该:
Bindings.bindBidirectional(textProp, intProp, new NumberStringConverter());
我有类似的问题。 我试图将字符串转换为File-Object并返回。 但我使用了Bindings.bindBidirectional(…,…,java.text.Format)。 从字符串到文件的转换按预期工作,但在另一个方向上,结果为null。 我试着用你的例子,同样的结果! 我认为绑定机制中存在一个错误,或者我的java.text.Format实现错误。
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); } }
让事情按预期工作的唯一方法是按照Hendrik Ebbers的建议实现StringConverter。 谢谢你的提示!
我在Eclipse中尝试了你的代码并且必须转换转换器。 一切看起来都不错:
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)converter); intProp.set(2); System.out.println(textProp); textProp.set("8"); System.out.println(intProp); } }
输出是:
StringProperty [value:2]
IntegerProperty [值:8]
我认为这是一个错误。 无论如何你可以解决方法如下:
StringConverter sc = new IntegerStringConverter(); Bindings.bindBidirectional(textProp, intProp, sc);