How can i access my Objects in a vaadin tree?

Hey,

I`ve added my own objects into a vaadin tree like this:
Item item = container.addItem(planet); //where planet is from class Planet

If I get it right, only the string taken from planet.toString() will be added to my tree.

Now I need to access several methods/attributes of my object (e.g. getMoons() or getPlanetID()). How can I access my object by selecting this planet in my tree (via getValue() in my valueChanged-event) ?

Your object is added as-is to the container the tree uses. So to use it in a listener, you simply cast it:

Planet p = (Planet) tree.getValue();

The Tree component uses the toString()-method to display it’s items by default; but this can be changed e.g. by adding a caption-property to you container:

Tree tree = new Tree();
tree.addContainerProperty("caption", String.class, "");
tree.setItemCaptionPropertyId("caption");

Item i= tree.addItem(planet);
i.getItemProperty("caption").setValue(planet.getName());

Note that you have to add the property before adding any items.

You can also try the BeanItemContainer, that fills all properties for you when adding items.

Hey, i have tryed it but i get an exception as soon as i click on a tree item :

Cause: java.lang.ClassCastException: java.util.Collections$UnmodifiableSet cannot be cast to com.portal.PlanetsStrukt

Hi
You need to cast the returned value to Collection. Because you enabled multiselection.

Greets

Seting the tree to Multiselect = false helped to :slight_smile: thx