这两种布局的基本用法如下:
VerticalLayout vertical = new VerticalLayout (); vertical.addComponent(new TextField("Name")); vertical.addComponent(new TextField("Street address")); vertical.addComponent(new TextField("Postal code")); main.addComponent(vertical);
改成使用HorizontalLayout ,显示如下:
此外可以通过setSpacing() 来修改UI组件之间的空隙,setComponnetAlignment 来修改UI组件的对齐方式。
要注意的是,布局中UI组件的实际占据的大小和位置和UI组件自身宽度和长度设置的不同有所不同。
比如对于VerticalLayout来说,如果其高度使用Sizeable.SIZE_UNDEFINED 将其设为“未定义”,则其高度自适应其包含的UI组件的高度,同理HorizontalLayout 布局的宽度为“未定义”HorizontalLayout 宽度也取决于其所包含的其她UI组件。
注: 如果布局包含的UI组件使用了“百分比”来定义高度或宽度,则要求Layout必须定义对应的宽度或高度。但如果通过其中包含的某些UI组件可以确定布局的宽度或高度,在这种情况下可以不定义布局类的大小
比如:
// Vertical layout would normally have 100% width VerticalLayout vertical = new VerticalLayout(); // Shrink to fit the width of contained components vertical.setWidth(Sizeable.SIZE_UNDEFINED, 0); // Label has normally 100% width, but we set it as // undefined so that it will take only the needed space Label label = new Label("\u2190 The VerticalLayout shrinks to fit "+ "the width of this Label \u2192"); label.setWidth(Sizeable.SIZE_UNDEFINED, 0); vertical.addComponent(label); // Button has undefined width by default Button butt = new Button("\u2190 This Button takes 100% "+ "of the width \u2192"); butt.setWidth("100%"); vertical.addComponent(butt);
这个例子使用VerticalLayout 布局,将其宽度设为“未定义”,而Button的宽度设为“100%”,此时如果没有Label组件,则必须为这个VerticalLayout 指定宽度,否则无法知道这个“100%”是哪个的“100%”。Label组件的宽度为“未定义”,其宽度取决于其显示字符的长度,在这个例子中,Button的宽度设为“100%”,因此与Label等宽。
在指定指定布局大小的情况下,缺省情况是将其包含的UI组件均匀间隔排列。
例如使用HorizontalLayout,并指定其宽度为400px
HorizontalLayout fittingLayout = new HorizontalLayout(); fittingLayout.setWidth("400px"); fittingLayout.addComponent(new Button("Small")); fittingLayout.addComponent(new Button("Medium-sized")); fittingLayout.addComponent(new Button("Quite a big component")); mainWindow.addComponent(fittingLayout);
HorizontalLayout fittingLayout = new HorizontalLayout(); fittingLayout.setWidth("400px"); fittingLayout.addComponent(new Button("Small")); fittingLayout.addComponent(new Button("Medium-sized")); // This button will expand. Button expandButton = new Button("Expanding component"); // Use 100% of the expansion cell's width. expandButton.setWidth("100%"); // The component must be added to layout before setting the ratio. fittingLayout.addComponent(expandButton); // Set the component's cell to expand. fittingLayout.setExpandRatio(expandButton, 1.0f); mainWindow.addComponent(fittingLayout);
HorizontalLayout layout = new HorizontalLayout(); layout.setWidth("400px"); // Create three equally expanding components. String[] captions = { "Small", "Medium-sized", "Quite a big component" }; for (int i = 1; i <= 3; i++) { Button button = new Button(captions[i-1]); layout.addComponent(button); // Expand ratios are 1:2:3. layout.setExpandRatio(button, i * 1.0f); }