The BorderLayout divides a container's space into five areas: north, south, east, west, and center.
When using BorderLayout, we need to specify to which of the five areas we want to add the component.
The BorderLayout class defines five constants to identify each of the five areas. The constants are NORTH, SOUTH, EAST, WEST, and CENTER.
For example, to add a button to the north area.
JButton northButton = new JButton("North"); container.add(northButton, BorderLayout.NORTH);
The default layout for the content pane of a JFrame is a BorderLayout.
The following code shows how to add five buttons to the content pane of a JFrame.
import java.awt.BorderLayout; import java.awt.Container; //from w w w . j a v a 2s . co m import javax.swing.JButton; import javax.swing.JFrame; public class Main { public static void main(String[] args) { JFrame frame = new JFrame("BorderLayout Test"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container container = frame.getContentPane(); // Add a button to each of the five areas of the BorderLayout container.add(new JButton("North"), BorderLayout.NORTH); container.add(new JButton("South"), BorderLayout.SOUTH); container.add(new JButton("East"), BorderLayout.EAST); container.add(new JButton("West"), BorderLayout.WEST); container.add(new JButton("Center"), BorderLayout.CENTER); frame.pack(); frame.setVisible(true); } }
We can add at most one component to each area of a BorderLayout. We can choose to leave some areas empty.
To add more than one component to an area of a BorderLayout, use nested containers.
If we do not specify the area for a component, it is added to the center. The following two statements have the same effect:
container.add(new JButton("Close")); container.add(new JButton("Close"), BorderLayout.CENTER);
BorderLayout computes the size of the components based on the area. It uses the preferred height of the component in north and south.
BorderLayout stretches the component's width horizontally according to the available space in north and south. It does not respect the preferred width of the components in north and south.
BorderLayout respects the preferred width of the components in east and west and gives them height necessary to fill the entire space vertically.
The component in the center area is stretched horizontally as well as vertically to fit the available space. The center area does not respect its component's preferred width and height.