BoxLayout arranges components either horizontally or vertically in a panel. You can control alignment and spacing of the components. Complicated layouts can be made by combining many panels, some with horizontal layout and some with vertical layouts.
are typically used:
Choose either a
horizontal layout (
vertical layout (
BoxLayout.Y_AXIS) for a JPanel.
JPanel p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); p.add(some_component);
Unlike other layouts, the panel/container must be passed to the BoxLayout constructor.
The above examples were created with this code, using either X_AXIS or Y_AXIS.
content.setLayout(new BoxLayout(content, BoxLayout.X_AXIS)); content.add(new JButton("Button 1")); content.add(new JButton("2")); content.add(new JButton("This is button three"));
Box class was designed to be a simple, and slightly more efficient, substitute for
JPanel with a
Because it doesn't support everything that
(eg, borders), I recommend using a
BoxLayout rather than
Box class has a number of necessary
methods for working with
Box is a
BoxLayout, all discussions of spacing and alignment
apply equally well to both JPanels with BoxLayouts and Boxes.
You can create the two kinds of boxes with:
import javax.swing.*; . . . Box vb = Box.createVerticalBox(); Box hb = Box.createHorizontalBox();
Boxes are lighter weight (ie, more efficient) than JPanel, but they don't support Borders. If you need borders, either use a JPanel with BoxLayout, or put the Box into a JPanel with a border.