Layout Managers

Throughout this text we assume that you have the following line in your code:

panel = new DrawPanel();

FlowLayout

This layout is the default one for Java applications. To create a FlowLayout use the following statements:

panel.setLayout(new FlowLayout());

or, alternatively,

FlowLayout layout = new FlowLayout();
panel.setLayout(layout);

The following image demonstrates the use of the FlowLayout manager. Click on the buttons to see how the GUI components are placed by the layout manager.

The method setAlignment(alignment) of class FlowLayout is used to align each line left, center, or right. The valid values of the alignment argument are FlowLayout.LEFT, FlowLayout.RIGHT, or FlowLayout.CENTER. The default alignment is CENTER.

The next example shows what happens if the applicaion window is too narrow to accommodate all the three buttons in one line.

BorderLayout

The BorderLayout manager uses the following field names for embedding the GUI components:

North
WestCenterEast
South

To create a BorderLayout use the following statements:

panel.setLayout(new BorderLayout(dx, dy));

or, alternatively,

BorderLayout layout = new BorderLayout(dx, dy);
panel.setLayout(layout);

where dx, dy is the horizontal/vertical gap between the cells in pixels (default value is 1 pixel).

The setVisible() method can be used to show/hide a button (and any Swing component, in general).

The following image demonstrates the use of the BorderLayout manager.

GridLayout

The GridLayout manager divides a container into a grid so that components can be places in rows and columns. Every component in GridLayout has the same width and height. Components are added to a GridLayout starting at the top-left cell of the grid and proceeding left to right until the row is full. Then the process continues left to right on the next row of the grid and so on.

To create a GridLayout use the following statements:

panel.setLayout(new GridLayout(r, c, dx, dy));

or, alternatively,

GridLayout layout = new GridLayout(r, c, dx, dy);
panel.setLayout(layout);

where r/c is the number of rows/columns, and dx/dy is the horizontal/vertical gap between the cells in pixels (default value is 1 pixel).

The following image demonstrate the layout in action.