2017-08-28 2 views
0

私はいつもimportantTree.get().getColor()に等しいタイプColorの別のObjectPropertyを作りたいObjectProperty ...JavaFX - 別のObjectProperty内のメンバーにObjectPropertyをバインドしますか?

ObjectProperty<Tree> importantTree = new SimpleObjectProperty(); 

を持ってTree

public class Tree 
{ 
    private Color c; 

    public Color getColor() 
    { 
     return c; 
    } 
} 

というクラスを持っています。ツリーが変わるたびに、もう1つのObjectPropertyをツリーの色に変更します。

たとえば、

ObjectProperty<Tree> importantTree = new SimpleObjectProperty(); 
ObjectProperty<Color> importantTreesColor = ... 


Tree a = new Tree(Color.RED); 
Tree b = new Tree(Color.GREEN); 

importantTree.set(a); 
System.out.println(importantTreesColor.get()); // This should print RED. 

importantTree.set(b); 
System.out.println(importantTreesColor.get()); // This should print GREEN. 

答えて

1

だけでバインディングを使用します。

ObjectProperty<Tree> importantTree = new SimpleObjectProperty(); 
Binding<Color> importantTreesColor = Bindings.createObjectBinding(() -> 
    importantTree.get() == null ? null : importantTree.get().getColor(), 
    importantTree); 

Tree a = new Tree(Color.RED); 
Tree b = new Tree(Color.GREEN); 

importantTree.set(a); 
System.out.println(importantTreesColor.getValue()); // Prints RED. 

importantTree.set(b); 
System.out.println(importantTreesColor.getValue()); // Prints GREEN. 

ご希望の場合にも、

Binding<Color> importantTreesColor = new ObjectBinding<Color>() { 
    { bind(importantTree); } 
    @Override 
    protected Color computeValue() { 
     return importantTree.get()==null ? null : importantTree.get().getColor(); 
    } 
}; 

を行うことができます。

+0

バインディングとプロパティの違いは何ですか? – Hatefiend

+0

一般にプロパティを設定でき、ほとんどの実装には実際の値が含まれます。バインディングは、1つ以上の他の観測可能な値にバインドされているだけのものです。関連する[documentation](http://docs.oracle.com/javase/8/javafx/api/javafx/beans/binding/Binding.html)または[チュートリアル](http://www.oracle.com)を参照してください。/pls/topic/lookup?ctx = javase80&id = JFXBD107)。 –

+0

素晴らしいです、わかりました。いつものように、あなたは素晴らしいです。あなたがJavaFX haha​​について知っているすべての情報を吸収することができたら – Hatefiend

関連する問題