本文介绍了获得 Vaadin Tree Item 的兄弟姐妹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取 Vaadin 树中特定项目的兄弟姐妹.我可以这样做:

I need to get the siblings of a particular Item in a Vaadin Tree. I can do this:

Object itemId = event.getItemId();
Object parentId = tree.getParent( itemId );
Collection siblings = tree.getChildren( parentId );

但是当 itemId 是根之一时会出现问题,例如:

BUT there is a problem when the itemId is one of the roots, for instance:

item1
  childen1.1
  children1.2
item2
item3

当我想要 item1 的兄弟姐妹时.有什么帮助吗?

When I want siblings of item1. Any help?

推荐答案

当一个项没有父项(又名 tree.getParent(itemId) == null),那么它就是一个根,所以它的兄弟项是其他根项目,否则就像您说的那样,获取项目的父项,然后获取其子项.下面是一个可以帮助您入门的基本示例(请注意,所选节点也出现在兄弟节点列表中):

When an item has no parent (aka tree.getParent(itemId) == null) then it's a root, so its siblings are the other root items, otherwise just like you said, get the item's parent and then its children. Below is a basic sample that should get you started (please be aware that the selected node also appears in the list of siblings):

代码:

public class TreeSiblingsComponent extends VerticalLayout {
    public TreeSiblingsComponent() {
        Tree tree = new Tree();
        addComponent(tree);

        // some root items
        tree.addItem("1");
        tree.setChildrenAllowed("1", false);
        tree.addItem("2");
        tree.setChildrenAllowed("2", false);

        // an item with hierarchy
        tree.addItem("3");
        tree.addItem("4");
        tree.setChildrenAllowed("4", false);
        tree.setParent("4", "3");
        tree.addItem("5");
        tree.setChildrenAllowed("5", false);
        tree.setParent("5", "3");
        tree.expandItem("3");

        // another root
        tree.addItem("6");
        tree.setChildrenAllowed("6", false);

        // another item with children that have children
        tree.addItem("7");
        tree.addItem("8");
        tree.setParent("8", "7");
        tree.addItem("9");
        tree.setChildrenAllowed("9", false);
        tree.setParent("9", "8");
        tree.addItem("10");
        tree.setChildrenAllowed("10", false);
        tree.setParent("10", "8");
        tree.expandItemsRecursively("7");

        // label to display siblings on selection
        Label siblings = new Label("Nothing selected");
        siblings.setCaption("Siblings:");
        addComponent(siblings);

        tree.addItemClickListener(event -> {
            Object parent = tree.getParent(event.getItemId());
            if (parent == null) {
                // root items have no parent
                siblings.setValue(tree.rootItemIds().toString());
            } else {
                // get parent of selected item and its children
                siblings.setValue(tree.getChildren(parent).toString());
            }
        });
    }
}

结果:

这篇关于获得 Vaadin Tree Item 的兄弟姐妹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-09 04:39