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, possibly 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 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 add( ) method that
takes an additional argument as a constraint. This specifies the name
of a position within the BorderLayout.
The following
application sets a
BorderLayout layout and adds our five buttons
again, named for their locations; the result is shown in Figure 16.4.
//file: Border1.java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Border1 extends JPanel { public Border1( ) { setLayout(new BorderLayout( )); add(new JButton("North"), BorderLayout.NORTH); add(new JButton("South"), BorderLayout.SOUTH); add(new JButton("East"), BorderLayout.EAST); add(new JButton("West"), BorderLayout.WEST); add(new JButton("Center"), BorderLayout.CENTER); } public ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access