GridLayout 布局使用網(wǎng)格來布置其中的 UI 組件。每個網(wǎng)格提供行,列來定義。每個 UI 組件可以占據(jù)一個或多個網(wǎng)格。由網(wǎng)格的坐標(biāo)(x1,y1,x2,y2)來定義。 GridLayout 布局內(nèi)部使用一個游標(biāo)(cursor)來記錄當(dāng)前的網(wǎng)格位置,GridLayout 布局添加 UI 組件的順序為從左到右,從上到下。如果游標(biāo)越過當(dāng)前網(wǎng)格的右下角,GridLayout 布局自動添加一行。 下例為 GridLayout 布局的基本用法,addComponent 第一個參數(shù)為所添加的 UI 組件對象,第二個參數(shù)可選,指定 UI 組件添加的網(wǎng)格坐標(biāo)??梢允褂脝蝹€坐標(biāo)或是一個區(qū)域。網(wǎng)格坐標(biāo)從0開始。
// Create a 4 by 4 grid layout.
GridLayout grid = new GridLayout(4, 4);
grid.addStyleName("example-gridlayout");
// Fill out the first row using the cursor.
grid.addComponent(new Button("R/C 1"));
for (int i = 0; i < 3; i++) {
grid.addComponent(new Button("Col " + (grid.getCursorX() + 1)));
}
// Fill out the first column using coordinates.
for (int i = 1; i < 4; i++) {
grid.addComponent(new Button("Row " + i), 0, i);
}
// Add some components of various shapes.
grid.addComponent(new Button("3x1 button"), 1, 1, 3, 1);
grid.addComponent(new Label("1x2 cell"), 1, 2, 1, 3);
InlineDateField date = new InlineDateField("A 2x2 date field");
date.setResolution(DateField.RESOLUTION_DAY);
grid.addComponent(date, 2, 2, 3, 3);
http://wiki.jikexueyuan.com/project/vaadin-web-development-tutorial/images/79.png" alt="" />
GridLayout 布局缺省使用“未定義”寬度和高度,因此缺省自適應(yīng)其所包含的 UI 組件。如果使用指定大小或是比例,其可使用的選項類同Vaadin Web應(yīng)用開發(fā)教程(29):UI布局-VerticalLayout和HorizontalLayout布局
類似 VerticalLayout 和 HorizontalLayout 布局也可以為 UI 組件指定擴(kuò)展比例,讓某些 UI 組件占據(jù) GridLayout 布局剩余空間??梢酝ㄟ^ setRowExpandRatio()和 setColumnExpandRatio()為行和列分別制定擴(kuò)展(權(quán)重)比例。第一個參數(shù)為行或列的坐標(biāo),第二個參數(shù)為權(quán)重。 如下例:
GridLayout grid = new GridLayout(3,2);
// Layout containing relatively sized components must have
// a defined size, here is fixed size.
grid.setWidth("600px");
grid.setHeight("200px");
// Add some content
String labels [] = {
"Shrinking column<br/>Shrinking row",
"Expanding column (1:)<br/>Shrinking row",
"Expanding column (5:)<br/>Shrinking row",
"Shrinking column<br/>Expanding row",
"Expanding column (1:)<br/>Expanding row",
"Expanding column (5:)<br/>Expanding row"
};
for (int i=0; i<labels.length; i++) {
Label label = new Label(labels[i], Label.CONTENT_XHTML);
label.setWidth(null); // Set width as undefined
grid.addComponent(label);
}
// Set different expansion ratios for the two columns
grid.setColumnExpandRatio(1, 1);
grid.setColumnExpandRatio(2, 5);
// Set the bottom row to expand
grid.setRowExpandRatio(1, 1);
// Align and size the labels.
for (int col=0; col<grid.getColumns(); col++) {
for (int row=0; row<grid.getRows(); row++) {
Component c = grid.getComponent(col, row);
grid.setComponentAlignment(c, Alignment.TOP_CENTER);
// Make the labels high to illustrate the empty
// horizontal space.
if (col != 0 || row != 0)
c.setHeight("100%");
}
}
http://wiki.jikexueyuan.com/project/vaadin-web-development-tutorial/images/80.png" alt="" />