我想做的就是将一个浮动绑定到另一个:
import javafx.beans.property.FloatProperty;
import javafx.beans.property.SimpleFloatProperty;
public class BindingTest
{
public static void main(String[] args)
{
float bound=0;
float binder= -1;
FloatProperty boundP= new SimpleFloatProperty(bound);
FloatProperty binderP=new SimpleFloatProperty(binder);
binderP.bind(boundP);
System.out.println("Before: \n\tbinder: " +binder + "\n\tbound: " + bound);
binder= 23;
System.out.println("After: \n\tbinder: " +binder + "\n\tbound: " + bound);
}
}
如果您懒得运行它,当变量bound
更改为值23时,变量binder
将不会更新。
我究竟做错了什么?
谢谢!
答案 0 :(得分:2)
所以我认为你对属性如何运作有错误的想法。我为更好的理解做了一个例子:
import javafx.beans.binding.Bindings;
import javafx.beans.binding.NumberBinding;
import javafx.beans.property.FloatProperty;
import javafx.beans.property.SimpleFloatProperty;
public class Test {
public static void main(String... args) {
FloatProperty dummyProp = new SimpleFloatProperty(0);
FloatProperty binderP = new SimpleFloatProperty(-1);
//Means boundP = dummyProp + binderP
NumberBinding boundP = Bindings.add(binderP, dummyProp);
System.out.format("%f + %f = %f%n", dummyProp.floatValue(), binderP.floatValue(), boundP.floatValue());
dummyProp.set(2);
System.out.format("%f + %f = %f%n", dummyProp.floatValue(), binderP.floatValue(), boundP.floatValue());
// dummyProp is equal to binderP but dummyProp is a read-only value
dummyProp.bind(binderP);
System.out.format("%f, %f%n", dummyProp.floatValue(), binderP.floatValue());
// throws an exception because dummyProp is bound to binderP
// dummyProp.set(5);
binderP.set(5f);
System.out.format("%f, %f%n", dummyProp.floatValue(), binderP.floatValue());
dummyProp.unbind();
// dummyProp == binderP always
dummyProp.bindBidirectional(binderP);
System.out.format("%f, %f%n", dummyProp.floatValue(), binderP.floatValue());
dummyProp.set(3f);
System.out.format("%f, %f%n", dummyProp.floatValue(), binderP.floatValue());
binderP.set(10f);
System.out.format("%f, %f%n", dummyProp.floatValue(), binderP.floatValue());
// boundP always consists of the sum
System.out.format("%f%n", boundP.floatValue());
}
}