Important Notice - Forums is archived
To simplify things and help our users to be more productive, we have archived the current forum and focus our efforts on helping developers on Stack Overflow. You can post new questions on Stack Overflow or join our Discord channel.

Vaadin lets you build secure, UX-first PWAs entirely in Java.
Free ebook & tutorial.
how to default select items in a tree
Hi All
I was wondering how to select by default certain items. If I loop through my items like
final Tree tree = new Tree(.....) ;
Iterator it = tree.getItemIds().iterator() ;
while( it.hasNext()) {
Item itm = tree.getItem( it.next() ) ;
System.out.println("item title is " + itm.getItemProperty("title")) ;
tree.select(itm);
}
In the above code I tried to have all items to be selected by default. But tree.select(..) doesn't select anything!
Any suggestions how to select an item ?
cheers
Just a couple of checks - is your tree is allowed to do multi selects and be immediate ?
Yes, here are some snippets:
final Tree tree = new Tree(null, createHierarchicalContainer() ) ;
tree.setMultiSelect(true);
tree.setImmediate(true);
.....
public HierarchicalContainer createHierarchicalContainer() {
treeContainer = new HierarchicalContainer();
treeContainer.addContainerProperty("title", String.class, null);
treeContainer.addContainerProperty("id", Integer.class, null);
Item item;
int itemId = 0;
for (int i = start; i < end; i++) {
item = treeContainer.addItem(itemId);
item.getItemProperty("title").setValue(sources.get(i).getTitle());
item.getItemProperty("id").setValue(sources.get(i).getId());
treeContainer.setChildrenAllowed(itemId, true);
itemId++;
List<Category> cats = sources.get(i).getCategories();
for (int j = 0; j < cats.size(); j++) {
item = treeContainer.addItem(itemId);
item.getItemProperty("title").setValue(cats.get(j).getTitle());
item.getItemProperty("id").setValue(cats.get(j).getId());
treeContainer.setParent(itemId, itemId - j -1);
treeContainer.setChildrenAllowed(itemId, false);
itemId++;
}
}
return treeContainer;
}
}
jeanluca Scaljeri:
final Tree tree = new Tree(.....) ; Iterator it = tree.getItemIds().iterator() ; while( it.hasNext()) { Item itm = tree.getItem( it.next() ) ; System.out.println("item title is " + itm.getItemProperty("title")) ; tree.select(itm); }
In the above code I tried to have all items to be selected by default. But tree.select(..) doesn't select anything!
Tree.select(Object) takes an item ID, not an item, so you should use the value returned by the iterator.
On the other hand, to select all items, you could simply do tree.setValue(tree.getItemIds()). For a multi-selectable tree or table (or other AbstractSelect), the value is the selection as a Set, and setValue() should automatically copy the given Collection to a new set.
thnx for pointing that out!
I finally solved the problem by moving your code just before the statement where I add the tree to the layout object!
cheers