Skip to Content
Learning Java, 4th Edition
book

Learning Java, 4th Edition

by Patrick Niemeyer, Daniel Leuck
June 2013
Beginner
1007 pages
33h 32m
English
O'Reilly Media, Inc.
Content preview from Learning Java, 4th Edition

BoxLayout

Most layout managers are part of the java.awt package and were defined back when Java was first released. Swing adds a couple of new general-purpose layout managers in the javax.swing package; one is BoxLayout. This layout manager is useful for creating simple toolbars or vertical button bars. It lays out components in a single row or column. It is similar to FlowLayout except that it does not wrap components into new rows.

Although you can use BoxLayout directly, Swing includes a handy container called Box that takes care of the details for you. Every Box uses BoxLayout, but you don’t really have to worry about it; the Box class includes some very useful methods for laying out components.

You can create a horizontal or vertical box using Box’s static methods.

    Container horizontalBox = Box.createHorizontalBox();
    Container verticalBox = Box.createVerticalBox();

Once the Box is created, you can add() components as usual:

    Container box = Box.createHorizontalBox();
    box.add(new JButton("In the"));

Box includes several other static methods that create special invisible components that can be used to guide the BoxLayout. The first of these is glue; glue is really space between components in the Box. When the Box is resized, glue expands or contracts as more or less space is available. The other special invisible component type is a strut. Like glue, a strut represents space between components, but it doesn’t resize.

The following example creates a horizontal Box (shown in Figure 19-6 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Java, 6th Edition

Learning Java, 6th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck
Learning Java, 5th Edition

Learning Java, 5th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck
Head First Java, 3rd Edition

Head First Java, 3rd Edition

Kathy Sierra, Bert Bates, Trisha Gee
Java in a Nutshell, 7th Edition

Java in a Nutshell, 7th Edition

Benjamin J. Evans, David Flanagan

Publisher Resources

ISBN: 9781449372477Errata PageSupplemental Content