Get sibling of Vaadin Tree Item?

痴心易碎 提交于 2019-12-10 23:14:31

问题


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

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

item1
  childen1.1
  children1.2
item2
item3

When I want siblings of item1. Any help?


回答1:


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):

The code:

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

The result:



来源:https://stackoverflow.com/questions/38711628/get-sibling-of-vaadin-tree-item

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!