获得Vaadin Tree项目的兄弟姐妹?

时间:2016-08-02 04:11:07

标签: vaadin vaadin7

我需要在Vaadin树中获取特定物品的兄弟姐妹。我可以这样做:

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

但是当itemId是其中一个根时出现问题,例如:

item1
  childen1.1
  children1.2
item2
item3

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

1 个答案:

答案 0 :(得分:1)

当一个项目没有父项(又名tree.getParent(itemId) == null)时,它就是root,所以它的兄弟是其他根项,否则就像你说的那样,得到项目的父项然后它的孩子。以下是一个应该开始的基本示例(请注意所选节点也会出现在兄弟姐妹列表中):

代码:

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

结果:

Sibling selection