Laying Out Components within a Container |
Here's an applet that shows aBorderLayout
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 viewBorder.html
, specifyingswing.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 ofAppletButton
, or as an application. The first two lines of this code is actually unnecessary for this example, since it's in aJFrame
subclass and the content pane for theJFrame
already has an associatedBorderLayout
instance. However, the first line would be necessary if the code were in aJPanel
instead of aJFrame
.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 usesBorderLayout
, you must use the two-argument version of theadd
method, and the first argument must be"North"
,"South"
,"East"
,"West"
, or"Center"
. If you use the one-argument version ofadd
, 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 theJButton
s 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]
Laying Out Components within a Container |