Java Reference
In-Depth Information
Boxes and BoxLayout managers
The leftmost JFrame of Fig. 17.11 looks like it contains a JPanel in its center.
However, the center is really an instance of class Box . Like JPanel , Box has
Container as a superclass. But it uses a BoxLayout manager instead of a
FlowLayout manager.
The leftmost JFrame is an instance of class BoxDemo of Fig. 17.12. We
investigate its constructor.
The second statement creates and stores in variable b a Box object. The argu-
ment of the constructor call is a constant of layout manager BoxLayout , which
tells the layout manager to lay out the Box horizontally. Then, the four buttons
are added to Box b using a single-argument add procedure, just as with a
FlowLayout manager.
Following that, the JFrame 's content pane is stored in variable cp and the
components are added to content pane cp , with the Box object in the center.
Finally, the JFrame is packed.
When using a BoxLayout manager, components are added one at a time,
using the one-argument method add. But with a BoxLayout manager, the com-
ponents always stay in a row. They may get squished together, but they remain
in one row.
import java.awt.*;
import javax.swing.*;
public class BoxDemo extends JFrame {
/** Constructor: an invisible frame with title t , labels in the north and south,
and a four-button horizontal Box in the center. */
public BoxDemo(String t) {
super (t);
Box b= new Box(BoxLayout.X_AXIS);
b.add( new JButton("0"));
b.add( new JButton("1"));
b.add( new JButton("2"));
b.add( new JButton("3"));
Container cp= getContentPane();
cp.add( new JLabel("north"), BorderLayout.NORTH);
cp.add( new JLabel("south"), BorderLayout.SOUTH);
cp.add(b, BorderLayout.CENTER);
Figure 17.12:
Class BoxDemo
Search WWH ::

Custom Search