我只是尝试绑定Integer和String属性。经过一些谷歌搜索后,应该可以使用以下两种方法之一:
public static void bindBidirectional(Property stringProperty,
Property otherProperty,StringConverter converter)
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);
}
}
答案 0 :(得分:17)
类型混淆的简单问题
Bindings.bindBidirectional(textProp, intProp, new IntegerStringConverter());
应该是:
Bindings.bindBidirectional(textProp, intProp, new NumberStringConverter());
答案 1 :(得分:3)
我在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<Number>)converter);
intProp.set(2);
System.out.println(textProp);
textProp.set("8");
System.out.println(intProp);
}
}
输出结果为:
StringProperty [value:2]
IntegerProperty [value:8]
答案 2 :(得分:3)
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。谢谢你的提示!
答案 3 :(得分:0)
我认为这是一个错误。无论如何,你可以解决方法:
StringConverter sc = new IntegerStringConverter();
Bindings.bindBidirectional(textProp, intProp, sc);