Java examples for Swing:BorderLayout
The default layout for the content pane of a JFrame is a BorderLayout.
The BorderLayout divides a container's space into five areas: north, south, east, west, and center.
To add a component with a BorderLayout, specify one of the five areas.
BorderLayout class has five constants to identify each of the five areas.
The constants are NORTH, SOUTH, EAST, WEST, and CENTER.
To add a button to the north area.
JButton northButton = new JButton("North"); container.add(northButton, BorderLayout.NORTH);
The following code adds five buttons to the content pane of a JFrame.
import java.awt.BorderLayout; import java.awt.Container; 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();/*from ww w .j a v a 2 s .co m*/ frame.setVisible(true); } }
You may leave some areas empty.
If you 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);
One area in BorderLayout can only have one component.
container.add(new JButton("Close"), BorderLayout.NORTH); container.add(new JButton("Help"), BorderLayout.NORTH);
Only JButton("Help") is there.