Vaadin Web应用开发教程(32):UI布局-Panel

jerry VaadinWeb 2015年11月25日 收藏

Panel 为带有边框和标题的简单容器类,它的客户区为一布局对象,其缺省布局方式为VerticalLayout,可以通过setContent来修改缺省布局。
Panel的标题可以由图标和文字构成。

  1. // Create a panel with a caption.
  2. final Panel panel = new Panel("Contact Information");
  3. panel.addStyleName("panelexample");
  4. // The width of a Panel is 100% by default, make it
  5. // shrink to fit the contents.
  6. panel.setWidth(Sizeable.SIZE_UNDEFINED, 0);
  7. // Create a layout inside the panel
  8. final FormLayout form = new FormLayout();
  9. // Have some margin around it.
  10. form.setMargin(true);
  11. // Add some components
  12. form.addComponent(new TextField("Name"));
  13. form.addComponent(new TextField("Email"));
  14. // Set the layout as the root layout of the panel
  15. panel.setContent(form);


对于Panel来说,如果其大小为“未定义”,那么它会自动适应其所包含的UI组件的大小。但如果它有固定大小而其中所需显示内容过大,则会自动显示滚动条。
如下例在Panel中显示一幅图像:

  1. // Serve the image from the theme
  2. Resource rsrc = new ThemeResource("img/embedded-journalist.jpg");
  3. // Display the image without caption
  4. Embedded image = new Embedded(null, rsrc);
  5. image.setSizeUndefined(); // Actually the default
  6. // The panel will give it scrollbars. The root layout
  7. // (VerticalLayout) must have undefined width to make the
  8. // horizontal scroll bar appear.
  9. Panel panel = new Panel("Embedding");
  10. panel.setWidth("400px");
  11. panel.setHeight("300px");
  12. panel.getContent().setSizeUndefined();
  13. panel.addComponent(image);
  14. layout.addComponent(panel);


Panel的滚动条也可以使用程序来控制,首先通过 setScrollable(true) 打开滚动条控制,然后使用 setScrollTop()和setScrollLeft()来控制滚动条的位置。

  1. final Panel panel = new Panel("Scrolling Panel");
  2. panel.setHeight("300px");
  3. panel.setWidth("400px");
  4. panel.getContent().setHeight("1000px");
  5. panel.setScrollable(true);
  6. layout.addComponent(panel);
  7.  
  8. HorizontalLayout scrollButtons = new HorizontalLayout();
  9. layout.addComponent(scrollButtons);
  10. Button scrollUp = new Button("Scroll Up");
  11. scrollUp.addListener(new Button.ClickListener() {
  12. public void buttonClick(ClickEvent event) {
  13. int scrollPos = panel.getScrollTop() - 250;
  14. if (scrollPos < 0)
  15. scrollPos = 0;
  16. panel.setScrollTop(scrollPos);
  17. }
  18. });
  19. scrollButtons.addComponent(scrollUp);
  20. Button scrollDown = new Button("Scroll Down");
  21. scrollDown.addListener(new Button.ClickListener() {
  22. public void buttonClick(ClickEvent event) {
  23. int scrollPos = panel.getScrollTop();
  24. if (scrollPos > 1000)
  25. scrollPos = 1000;
  26. panel.setScrollTop(scrollPos + 250);
  27. }
  28. });
  29. scrollButtons.addComponent(scrollDown);