是否在TreeCell中自动删除绑定

时间:2014-06-19 14:56:19

标签: java javafx-8

我有TreeView,它上面有一个单元工厂。我返回的TreeCells显示如下:

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

请注意,我没有设置文本,但我将textProperty绑定到StringBinding。这在正常情况下工作正常,但我想知道在TreeCell中使用它是否可以。

TreeCell会在需要时进行回收,因此我想知道当发生这种情况时,是否会自动删除绑定或是否需要手动删除它?

我不想要每个TreeCell附加100个绑定的情况。

1 个答案:

答案 0 :(得分:1)

虽然没有记录,但在创建新绑定之前,调用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(...)方法中无条件地调用它意味着您不依赖于未记录的行为,并且任何效率损失都可能很小。