Java – Border Layout in AWT

In Border layout we can add components (such as text fields, buttons, labels etc) to the five specific regions. These regions are called PAGE_START, LINE_START, CENTER, LINE_END, PAGE_END. Refer the diagram below to understand their location on a Frame.

The diagram above is the output of below code, where I have added five buttons (which have same name as regions in which they have been placed) to the five regions of Border Layout. You can add any component of your choice in a similar manner.

Note: The name of buttons in the example above are intentionally set same as region names, this is just for educational purpose, you can name them as per your wish and requirement.

What if you want spaces among regions?

In the example above, we do not have any space among regions; however we can have horizontal as well as vertical space between regions. There are two ways to do it –
1) Notice the statement setLayout(new BorderLayout( )); in the example above, if you change it to this: setLayout(new BorderLayout(50,20)); then the output Frame would look like the image below. Here 50 is horizontal gap and 20 is vertical gap.

Method details:public BorderLayout(int hgap, int vgap)
Constructs a border layout with the specified gaps between components. The horizontal gap is specified by hgap and the vertical gap is specified by vgap.
Parameters:hgap – the horizontal gap.vgap – the vertical gap.
2) You can also do it by using setHgap(int hgap) method for horizontal gap between components and setVgap(int vgap) method for vertical gap.