Vaadin Web应用开发教程(30):UI布局-GridLayout布局

jerry VaadinWeb 2015年11月25日 收藏

GridLayout布局使用网格来布置其中的UI组件。每个网格提供行,列来定义。每个UI组件可以占据一个或多个网格。由网格的坐标(x1,y1,x2,y2)来定义。
GridLayout布局内部使用一个游标(cursor)来记录当前的网格位置,GridLayout布局添加UI组件的顺序为从左到右,从上到下。如果游标越过当前网格的右下角,GridLayout布局自动添加一行。
下例为GridLayout布局的基本用法,addComponent 第一个参数为所添加的UI组件对象,第二个参数可选,指定UI组件添加的网格坐标。可以使用单个坐标或是一个区域。网格坐标从0开始。

  1. // Create a 4 by 4 grid layout.
  2. GridLayout grid = new GridLayout(4, 4);
  3. grid.addStyleName("example-gridlayout");
  4.  
  5. // Fill out the first row using the cursor.
  6. grid.addComponent(new Button("R/C 1"));
  7. for (int i = 0; i < 3; i++) {
  8. grid.addComponent(new Button("Col " + (grid.getCursorX() + 1)));
  9. }
  10.  
  11. // Fill out the first column using coordinates.
  12. for (int i = 1; i < 4; i++) {
  13. grid.addComponent(new Button("Row " + i), 0, i);
  14. }
  15. // Add some components of various shapes.
  16. grid.addComponent(new Button("3x1 button"), 1, 1, 3, 1);
  17. grid.addComponent(new Label("1x2 cell"), 1, 2, 1, 3);
  18. InlineDateField date = new InlineDateField("A 2x2 date field");
  19. date.setResolution(DateField.RESOLUTION_DAY);
  20. grid.addComponent(date, 2, 2, 3, 3);

GridLayout布局缺省使用“未定义”宽度和高度,因此缺省自适应其所包含的UI组件。如果使用指定大小或是比例,其可使用的选项类同Vaadin Web应用开发教程(29):UI布局-VerticalLayout和HorizontalLayout布局

类似VerticalLayout和HorizontalLayout布局也可以为UI组件指定扩展比例,让某些UI组件占据GridLayout布局剩余空间。可以通过setRowExpandRatio()和setColumnExpandRatio()为行和列分别制定扩展(权重)比例。第一个参数为行或列的坐标,第二个参数为权重。
如下例:

  1. GridLayout grid = new GridLayout(3,2);
  2.  
  3. // Layout containing relatively sized components must have
  4. // a defined size, here is fixed size.
  5. grid.setWidth("600px");
  6. grid.setHeight("200px");
  7.  
  8. // Add some content
  9. String labels [] = {
  10. "Shrinking column<br/>Shrinking row",
  11. "Expanding column (1:)<br/>Shrinking row",
  12. "Expanding column (5:)<br/>Shrinking row",
  13. "Shrinking column<br/>Expanding row",
  14. "Expanding column (1:)<br/>Expanding row",
  15. "Expanding column (5:)<br/>Expanding row"
  16. };
  17. for (int i=0; i<labels.length; i++) {
  18. Label label = new Label(labels[i], Label.CONTENT_XHTML);
  19. label.setWidth(null); // Set width as undefined
  20. grid.addComponent(label);
  21. }
  22.  
  23. // Set different expansion ratios for the two columns
  24. grid.setColumnExpandRatio(1, 1);
  25. grid.setColumnExpandRatio(2, 5);
  26.  
  27. // Set the bottom row to expand
  28. grid.setRowExpandRatio(1, 1);
  29.  
  30. // Align and size the labels.
  31. for (int col=0; col<grid.getColumns(); col++) {
  32. for (int row=0; row<grid.getRows(); row++) {
  33. Component c = grid.getComponent(col, row);
  34. grid.setComponentAlignment(c, Alignment.TOP_CENTER);
  35. // Make the labels high to illustrate the empty
  36. // horizontal space.
  37. if (col != 0 || row != 0)
  38. c.setHeight("100%");
  39. }
  40. }