Box, BoxLayout Example
A Box is a container that uses BoxLayout as its layout manager. A Box can have its components laid out horizontally or vertically. We show one of each Box layouts, and use two different styles of constructor.
Glue and struts can be used for spacing components in the Box.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Box Example
import java.awt.*;
import javax.swing.*;
class BoxExample {
public static void main(String[] args) {
Box b0 = new Box(BoxLayout.Y_AXIS);
Box b1 = Box.createHorizontalBox();
for(int i=0;i<5;++i) {
b0.add(new JLabel("label "+i,JLabel.CENTER));
b1.add(new JButton("button "+i));
}
JFrame frame = new JFrame();
Container cp = frame.getContentPane();
cp.setLayout(new FlowLayout());
cp.add(b0);
cp.add(b1);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
9-10 Here are the two ways of constructing a Box container. Either style will do.
The second one, for example, could just as well have been written:
Box b1 = new Box(BoxLayout.X_AXIS);
