Previous | Next | Trail Map | Creating a User Interface | 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:

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

Below is the code that 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 line shown below is actually unnecessary for this example, since it's in a Window subclass and each Window already has an associated BorderLayout instance. However, the first line would be necessary if the code were in a Panel instead of a Window.

setLayout(new BorderLayout());
setFont(new Font("Helvetica", Font.PLAIN, 14));
   
add("North", new Button("North"));
add("South", new Button("South"));
add("East", new Button("East"));
add("West", new Button("West"));
add("Center", new Button("Center"));

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.

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

public BorderLayout(int horizontalGap, int verticalGap)


Previous | Next | Trail Map | Creating a User Interface | Laying Out Components within a Container