【发布时间】:2014-09-04 01:41:37
【问题描述】:
我有一个目标,其中有一个目标列表。一个目标有一个策略列表。战略有一个战术列表。一个策略有一个任务列表。
我希望能够在 TreeView 中显示它,并且我希望树与项目同步。也就是说,如果我删除了一个目标,那么该目标及其子项也会从 TreeView 中消失。
到目前为止,这是我一直在尝试的。
/**
* The base class for all PlanItems, which include ActionItems down to
* ActionTasks, and Objectives down to Tasks.
*
* @author Toni-Tran
*/
public class PlanItem implements Comparable<PlanItem> {
protected ObservableList<PlanItem> childPlanItems = FXCollections
.observableArrayList();
protected TreeItem<PlanItem> treeItem = new TreeItem<>(this);
这是所有这些项目的基类。在其构造函数中:
public PlanItem() {
CustomBinding.bindLists(treeItem.getChildren(), childPlanItems, PlanItem::getTreeItem);
}
我正在使用我的自定义绑定,它将两个不同对象的列表绑定在一起。 (或者,我可以使用 EasyBind)。
/**
* Binds a source list's elements to a destination list. Any changes made in
* the source list will reflect in the destination list.
*
* @param <SRC> The source list's object type.
* @param <DEST> The destination list's object type.
* @param dest The destination list that will be bound to the src list.
* @param src The source list to watch for changes, and propagate up to the
* destination list.
* @param transformer A function that will transform a source list data
* type, A, into a destination list data type, B.
*/
public static <SRC extends Object, DEST extends Object> void bindLists(
ObservableList<DEST> dest, ObservableList<SRC> src, Function<SRC, DEST> transformer) {
/*Add the initial data into the destination list.*/
for (SRC a : src) {
dest.add(transformer.apply(a));
}
/*Watch for future data to add to the destination list. Also watch for removal
of data form the source list to remove its respective item in the destination
list.*/
src.addListener((ListChangeListener.Change<? extends SRC> c) -> {
while (c.next()) {
/*Watch for removed data.*/
if (c.wasRemoved()) {
for (SRC a : c.getRemoved()) {
int from = c.getFrom();
dest.remove(from);
}
}
/*Watch for added data.*/
if (c.wasAdded()) {
for (SRC a : c.getAddedSubList()) {
int indexAdded = src.indexOf(a);
dest.add(indexAdded, transformer.apply(a));
}
}
}
});
}
我不确定这是否是正确的方法。子项列表通常是扩展 PlanItem 的对象列表,而不仅仅是 PlanItem 本身。那不应该是ObservableList<? extends PlanItem>吗?这样做会使我的其余代码变得复杂。
计划是创建一个包装 PlanItem 的 TreeItem。然后,将 TreeItem 的子 TreeItems 同步到 PlanItem 的子 PlanItems。这也对每个嵌套的 PlanItem 递归重复。
【问题讨论】:
标签: java inheritance javafx treeview javafx-8