Previous | Next | Trail Map | Creating a User Interface (with Swing) | Laying Out Components within a Container

How to Use BorderLayout

Here's an applet that shows a BorderLayout(in the API reference documentation) in action.


Your browser can't run 1.0 Java applets, so here's a picture of the window the program brings up:


Note: Because the preceding applet runs using Java Plug-in 1.1.1, it is a Swing 1.0.3 version of the applet. To run the Swing 1.1 Beta 3 version of the applet, you can use the JDK Applet Viewer to view Border.html, specifying swing.jar in the Applet Viewer's class path. For more information about running applets, refer to About Our Examples.

As the above applet shows, a BorderLayout has five areas: north, south, east, west, and center. If you enlarge the window, the center area gets as much of the available space as possible. The other areas expand only as much as necessary to fill all available space.

The following code creates the BorderLayout and the components it manages. Here's the whole program. The program runs either within an applet, with the help of AppletButton, or as an application. The first two lines of this code is actually unnecessary for this example, since it's in a JFrame subclass and the content pane for the JFrame already has an associated BorderLayout instance. However, the first line would be necessary if the code were in a JPanel instead of a JFrame.

JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());

contentPane.add("North", new JButton("North"));
contentPane.add("South", new JButton("South"));
contentPane.add("East", new JButton("East"));
contentPane.add("West", new JButton("West"));
contentPane.add("Center", new JButton("Center"));

setContentPane(contentPane);


Important: When adding a component to a container that uses BorderLayout, you must use the two-argument version of the add method, and the first argument must be "North", "South", "East", "West", or "Center". If you use the one-argument version of add, or if you specify an invalid first argument, your component might not be visible.

[PENDING: Actually, you can and probably should use add(component, BorderLayout.XXXX).]


By default, a BorderLayout puts no gap between the components it manages. In the applet above, any apparent gaps are the result of the JButtons reserving extra space around their apparent display area. You can specify gaps (in pixels) using the following constructor:

public BorderLayout(int horizontalGap, int verticalGap)

Examples that Use BorderLayout

[PENDING]


Previous | Next | Trail Map | Creating a User Interface (with Swing) | Laying Out Components within a Container