Layout Managers

Beyond these specialty panes with their dedicated layout managers, the Swing package also includes some general layout managers you can use with your own code. You can use the new BoxLayout to make things like toolbars and OverlayLayout to make things like layered labels.
 
The BoxLayout class is a manager that gives you one row or column to put everything in. It’s great for toolbars and button ribbons. It also comes with its very own convenience container called Box. The Box class is a lightweight container that requires a BoxLayout manager. While you can certainly use the BoxLayout class to control your own panel, frame, or other container, the Box class provides several shortcuts for dealing with components in a boxed layout. You’ll often find that using a Box is easier than creating a panel or frame that you control with a BoxLayout manager.
 

The Box Class

Let’s start with a look at the convenience container that puts the BoxLayout manager to use. The Box class is a lightweight container object whose primary purpose is to let you add components to a horizontal or vertical box without having to think about getting the constraints right. (As of SDK 1.4, Box extends JComponent.) You use the normal Container.add( ) method to place components in the box. Components are placed left to right (or top to bottom) in the order you add them.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class HBoxWithGlue extends JFrame {

	public HBoxWithGlue() {
		super("Box & Glue Frame");
		setSize(350, 100);
		Box box = Box.createHorizontalBox();
		setContentPane(box);
		box.add(Box.createHorizontalGlue());
		for (int i = 0; i < 3; i++) {
			Button b = new Button("B" + i);
			box.add(b);
		}
		box.add(Box.createHorizontalGlue());
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setVisible(true);
	}

	public static void main(String args[]) {
		HBoxWithGlue bt = new HBoxWithGlue();
	}
}