2015-11-18 34 views
0

所有我想要做的是一个浮动绑定到另一个:java8结合两个浮点数

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将不会被更新时,可变binder改为值23. 我在做什么错了? 谢谢!

+0

我认为你需要看看教程再次看到绑定是如何工作的:https://docs.oracle.com/javase/8/javafx/properties-binding -tutorial/binding.htm#sthref8 – Flown

+0

感谢Flown--在以下回答中张贴的回复 – Tel

+0

你知道什么*按价值*打电话吗? – Holger

回答

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()); 
    } 

} 
+0

谢谢,理解。非常感激! – Tel