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 ...
Get Java Cookbook 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.