BorderLayout Manager Example

BorderLayout Manager Example

setLayout(new BorderLayout());
setBackground(Color.red);

The layout to the frame is set to BorderLayout and infact even without this statement also program works because the default layout manager for the Frame is BorderLayout. The background color, red, is not seen as the default gap between the components is 0 pixels.

Setting gaps between the components

The default 0 pixel gap can be changed by setting the gaps explicitly.

setLayout(new BorderLayout(20, 40));

20 indicates horizontal gap and 40 indicates the vertical gap. Horizontal gap means the gap between the components within a row. Vertical gap means the gap between the components of two rows. Now the background color red is seen.

What happens when a component is not added?

When a component is not added, the neighboring components occupy the space and at no time the space is left empty. In the above program, miss one or two add() statements and observe how the remaining components behave. This understanding is very essential in layout management.

But if the center does not exist and all the remaining exist, the center space will be left empty and not occupied by the remaining.

The positions, used above, are in string form and can be replaced by BorderLayout static constants as follows..

  1. BorderLayout.NORTH in place of "North"
  2. BorderLayout.SOUTH in place of "South"
  3. BorderLayout.EAST in place of "East"
  4. BorderLayout.WEST in place of "West"
  5. BorderLayout.CENTER in place of "Center"

This type of addition is used in "AWT Choice".

Knowledge of Panels is also essential with layout managers to get the desired layout of components.

The frame you get do not close when clicked over the close icon on the title bar of the frame. It requires extra code close icon to work.

Leave a Comment

Your email address will not be published.