Search code examples
vaadinvaadin7

Get sibling of Vaadin Tree Item?


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?


Solution

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

    Sibling selection