Vaadin Web应用开发教程(19):UI组件-Tree 组件

jerry VaadinWeb 2015年11月25日 收藏

Tree 组件可以用来显示具有层次关系的数据源,比如文件系统。Tree组件的一个典型应用是作为菜单显示。

  1. final Object[][] planets = new Object[][]{
  2. new Object[]{"Mercury"},
  3. new Object[]{"Venus"},
  4. new Object[]{"Earth", "The Moon"},
  5. new Object[]{"Mars", "Phobos", "Deimos"},
  6. new Object[]{"Jupiter", "Io", "Europa", "Ganymedes",
  7. "Callisto"},
  8. new Object[]{"Saturn", "Titan", "Tethys", "Dione",
  9. "Rhea", "Iapetus"},
  10. new Object[]{"Uranus", "Miranda", "Ariel", "Umbriel",
  11. "Titania", "Oberon"},
  12. new Object[]{"Neptune", "Triton", "Proteus", "Nereid",
  13. "Larissa"}};
  14.  
  15. Tree tree = new Tree("The Planets and Major Moons");
  16.  
  17. // Add planets as root items in the tree.
  18. for (int i=0; i String planet = (String) (planets[i][0]);
  19. tree.addItem(planet);
  20.  
  21. if (planets[i].length == 1) {
  22. // The planet has no moons so make it a leaf.
  23. tree.setChildrenAllowed(planet, false);
  24. } else {
  25. // Add children (moons) under the planets.
  26. for (int j=1; j String moon = (String) planets[i][j];
  27.  
  28. // Add the item as a regular item.
  29. tree.addItem(moon);
  30.  
  31. // Set it to be a child.
  32. tree.setParent(moon, planet);
  33.  
  34. // Make the moons look like leaves.
  35. tree.setChildrenAllowed(moon, false);
  36. }
  37.  
  38. // Expand the subtree.
  39. tree.expandItemsRecursively(planet);
  40. }
  41. }
  42.  
  43. main.addComponent(tree);

当然你可以选择合适的Menu风格使得Tree看起来更像菜单,比如:

注:到这里你可能注意到到目前为止在介绍UI组件时文章都避免涉及CSS,Theme应用,这是为的使Vaadin应用开发更像开发桌面应用,后面会集中介绍主题的使用,对于一般应用你可以使用缺省主题。

同Field组件一样,你可以使用getValue,setValue 设置或取得Tree组件当前选中的Item项。Tree组件对应的Container类型为HierarchicalContainer.