Skip to main content
LWUIT Tutorial

Using Layouts

The form takes care of positioning the components. It uses a layout manager to decide where everything goes. For you AWT and Swing jocks, this should sound familar. Layout managers are great for mobile applications because they are good at adjusting to different screen sizes and filling the available space gracefully.

LWUIT includes five layout managers.

  • FlowLayout places components from left to right in rows, just like English text.
  • BorderLayout has a large center area and four smaller areas around the edges.
  • BoxLayout arranges components in a single row or column.
  • GridLayout places components in a grid.
  • More complex layouts can be accomplished using GroupLayout and its helper class Group.

You can build user interfaces that combine layouts by creating Containers that group components with a specific layout and then nesting different Containers together to create a complete user interface.

A variant of Container's addComponent() method allows you to provide a hint, or constraint, that is used when determining the position of each component. For example, the five regions of a BorderLayout are represented by the static variables NORTH, SOUTH, EAST, WEST, and CENTER. To add a component to the WEST (left) region, you would do this:

// Form f = ...
// Componeont c = ...
f.setLayout(new BorderLayout());
f.addComponent(BorderLayout.WEST, c);

This example shows how to combine a BorderLayout and a BoxLayout. The CENTER region of the BorderLayout contains the main content (an image) while the SOUTH region contains a button bar in an X_AXIS BoxLayout. Any components or containers placed in the center region stretch to fill the available space. In this case, the label is center-aligned so that the image appears in the center.

// Form f = ...
f.setLayout(new BorderLayout());

Image image = Image.createImage("/res/baldy.png");
Label bottomText = new Label(image);
bottomText.setAlignment(Component.CENTER);
bottomText.setText("Baldassare");
bottomText.setTextPosition(Component.BOTTOM);

Container buttonBar = new Container(new BoxLayout(BoxLayout.X_AXIS));
buttonBar.addComponent(new Button("Add"));
buttonBar.addComponent(new Button("Remove"));
buttonBar.addComponent(new Button("Edit"));
buttonBar.addComponent(new Button("Send"));
buttonBar.addComponent(new Button("Exit"));

f.addComponent(BorderLayout.CENTER, bottomText);
f.addComponent(BorderLayout.SOUTH, buttonBar);


Copyright © 2008 Sun Microsystems, Inc.
 
 
Close
loading
Please Confirm
Close