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.

Properties

Table 11-11 shows the properties of the Box class. You are not allowed to change a box’s layout manager, so the setLayout accessor ...

Get Java Swing, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.