Java 绑定是否在TreeCell中自动删除
我有一个树视图,上面有一个细胞工厂。我返回的TreeCells如下所示:Java 绑定是否在TreeCell中自动删除,java,javafx-8,Java,Javafx 8,我有一个树视图,上面有一个细胞工厂。我返回的TreeCells如下所示: import javafx.beans.binding.StringBinding; import javafx.collections.ObservableMap; import javafx.scene.control.TreeCell; public class TreeCellTest extends TreeCell<String> { private ObservableMap<St
import javafx.beans.binding.StringBinding;
import javafx.collections.ObservableMap;
import javafx.scene.control.TreeCell;
public class TreeCellTest extends TreeCell<String> {
private ObservableMap<String, StringBinding> lookup;
public TreeCellTest(ObservableMap<String, StringBinding> lookup) {
this.lookup = lookup;
}
@Override
protected void updateItem(String id, boolean empty) {
super.updateItem(id, empty);
if (empty) {
setText(null);
} else {
StringBinding stringBinding = lookup.get(id);
textProperty().bind(stringBinding);
}
}
}
导入javafx.beans.binding.StringBinding;
导入javafx.collections.observemap;
导入javafx.scene.control.TreeCell;
公共类TreeCellTest扩展了TreeCell{
私有映射查找;
公共TreeCellTest(可观察映射查找){
this.lookup=查找;
}
@凌驾
受保护的void updateItem(字符串id,布尔值为空){
super.updateItem(id,空);
if(空){
setText(空);
}否则{
StringBinding-StringBinding=lookup.get(id);
textProperty().bind(stringBinding);
}
}
}
请注意,我没有设置文本,而是将textProperty绑定到StringBinding。这在正常情况下工作正常,但我想知道是否可以在TreeCell中使用它
TreeCell会在需要时被回收,所以我想知道当这种情况发生时,绑定是否会被自动删除,或者我是否需要手动删除它
我不希望每个TreeCell都附加了100个绑定。虽然没有文档记录,但调用
bind(…)
似乎会在创建新绑定之前删除任何现有绑定
例如:
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class RebindingTest {
public static void main(String[] args) {
StringProperty text = new SimpleStringProperty();
StringProperty value1 = new SimpleStringProperty();
StringProperty value2 = new SimpleStringProperty();
text.addListener((obs, oldValue, newValue) -> System.out.printf("text changed from %s to %s%n", oldValue, newValue));
text.bind(value1);
value1.set("Set value 1");
text.bind(value2);
value2.set("Set value 2");
value1.set("Reset value 1");
}
}
因此,我认为要使代码正常工作,只需添加
textProperty().unbind();
到if(empty){…}
块
当然,在
updateItem(…)
方法中无条件地调用它意味着您不依赖未记录的行为,任何效率损失可能都是最小的。当然,我只调用textProperty().unbind();每次调用update方法时-我没想到-谢谢