Vaadin Web应用开发教程(27):UI组件-自定义组件

jerry VaadinWeb 2015年11月25日 收藏

Vaadin 支持自定义组件,典型的用法是将各种Vaadin内置的组件组合而成构成自定义组件。 创建自定义组件可以通过派生CustomComponent 然后调用setCompositionRoot 为自定义组件设置根容器。
例如:

  1. class MyComposite extends CustomComponent {
  2. public MyComposite(String message) {
  3. // A layout structure used for composition
  4. Panel panel = new Panel("My Custom Component");
  5. panel.setContent(new VerticalLayout());
  6. // Compose from multiple components
  7. Label label = new Label(message);
  8. label.setSizeUndefined(); // Shrink
  9. panel.addComponent(label);
  10. panel.addComponent(new Button("Ok"));
  11.  
  12. // Set the size as undefined at all levels
  13. panel.getContent().setSizeUndefined();
  14. panel.setSizeUndefined();
  15. setSizeUndefined();
  16.  
  17. // The composition root MUST be set
  18. setCompositionRoot(panel);
  19. }}


需要注意的是,如果希望自定义的组件自适应其所包含的其它UI组件,必须将容器的大小设为“未定义”,如上面的setSizeUndefined方法就是起这个作用。
构造自定义组件,也可以从其它Vaadin内置UI组件派生,或者利用Google Web Toolbit提供的组件创建全新的Vaadin UI组件(后面介绍)。