BorderLayout
BorderLayout is a little
more interesting. It tries to arrange objects in one of five geographical
locations, represented by constants in the BorderLayout class: NORTH, SOUTH, EAST, WEST, and CENTER, optionally with
some padding between. BorderLayout is
the default layout for the content panes of JWindow and JFrame objects. Because each component is
associated with a direction, BorderLayout can manage at most five components;
it squashes or stretches those components to fit its constraints. As we’ll
see in the second example, this means that you often want to have BorderLayout manage sets of components in their
own panels.
When we add a component to a container with a border layout, we need
to specify both the component and the position at which to add it. To do
so, we use an overloaded version of the container’s add() method that takes an additional argument
as a constraint. The constraint specifies
the name of a position within the BorderLayout.
The following application sets a BorderLayout and adds our five buttons again,
named for their locations:
//file: Border1.javaimportjava.awt.*;importjava.awt.event.*;importjavax.swing.*;publicclassBorder1extendsJPanel{publicBorder1(){setLayout(newBorderLayout());add(newJButton("North"),BorderLayout.NORTH);add(newJButton("South"),BorderLayout.SOUTH);add(newJButton("East"),BorderLayout.EAST);add(newJButton("West"),BorderLayout.WEST);add(newJButton("Center"),BorderLayout.CENTER);}public ...