gpt4 book ai didi

java - TreeCell 中的绑定(bind)是否会自动删除

转载 作者:行者123 更新时间:2023-12-01 12:49:55 25 4
gpt4 key购买 nike

我有一个 TreeView,上面设置了一个单元工厂。我返回的 TreeCell 显示如下:

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 绑定(bind)到 StringBinding。这在正常情况下工作得很好,但我想知道在 TreeCell 中使用它是否可以。

TreeCell 会在需要时回收,所以我想知道发生这种情况时绑定(bind)是否会自动删除,或者是否需要手动删除?

我不希望每个 TreeCell 都附加有 100 个绑定(bind)。

最佳答案

虽然没有记录,但调用 bind(...) 似乎会在创建新绑定(bind)之前删除任何现有绑定(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) { ... } block 。

当然,在 updateItem(...) 方法中无条件调用它意味着您不依赖于未记录的行为,并且任何效率损失可能都是最小的。

关于java - TreeCell 中的绑定(bind)是否会自动删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24309693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com