O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Program: Custom Layout Manager

Problem

None of the standard layout managers does quite what you need.

Solution

Roll your own. All you need to do is implement the methods of the java.awt.LayoutManager interface.

Discussion

While many people are intimidated by the thought of writing their own layout manager, it beats the alternative of using only “the big five” layouts (BorderLayout, CondLayout, FlowLayout, GridBagLayout, and GridLayout). BorderLayout isn’t quite flexible enough, and GridBaglayout is too complex for many applications. Suppose, for instance, that you wanted to lay out an arbitrary number of components in a circle. In a typical X Windows or MS-Windows application, you would write the geometry calculations within the code for creating the components to be drawn. This would work, but the code for the geometry calculations would be unavailable to anybody who needed it later. The LayoutManager interface is another great example of how the Java API’s design promotes code reuse: if you write the geometry calculations as a layout manager, then anybody needing this type of layout could simply instantiate your CircleLayout class to get circular layouts.

As another example, consider the layout shown in Figure 13-14, where the labels column and the textfield column have different widths. Using the big five layouts, there’s no good way to get this and still ensure that the columns line up and that you have control over the relative widths. Suppose you wanted the label field to take ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required