2015-11-18 73 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