Java Reference
In-Depth Information
Figure 10•5. Components laid out with a BorderLayout
Example 10•5: BorderLayoutPane.java
package com.davidflanagan.examples.gui;
import java.awt.*;
import javax.swing.*;
public class BorderLayoutPane extends JPanel {
String[] borders = {"North", "East", "South", "West", "Center"};
public BorderLayoutPane() {
// Use a BorderLayout with 10-pixel margins between components
this.setLayout(new BorderLayout(10, 10));
for(int i = 0; i < 5; i++) {
// Add children to the pane
this.add(new JButton(borders[i]),
// Add this component
borders[i]);
// Using this constraint
}
}
}
Box and BoxLayout
javax.swing.BoxLayout
is a simple but versatile layout manager that arranges its
children into a row or a column. The
javax.swing.Box
container uses
BoxLayout
;
it is much more common to work with the
Box
class than to use
BoxLayout
directly. What gives
Box
containers their versatility is the ability to add stretchy
space (
glue
) and rigid space (
struts
) to the layout. The
Box
class defines static
methods that make it particularly easy to create rows, columns, glue, and struts.
Example 10-6 creates several
Box
containers that demonstrate the capabilities of
BoxLayout
. The various boxes are themselves laid out using a
BorderLayout
. The
program output is shown in Figure 10-6. To keep you on your toes, Example 10-6
also demonstrates the use of Swing borders to add margins and decorations
around the outside of certain containers. Note that these borders can be added
around any Swing component or container; they are part of the
javax.swing.bor-
der
package and have nothing to do with the
BorderLayout
layout manager. See
javax.swing.border.Border
and the
setBorder()
method of
JComponent
.