Java Reference
In-Depth Information
Program: Custom AWT/Swing 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
Although 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
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 anoth-
er great example of how the Java API's design promotes code reuse: if you write the geo-
metry 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 14-18 , where the labels column and
the textfield column have different widths. Using the big five layouts, there's no good way to
ensure that the columns line up and that you have control over their relative widths. Suppose
you wanted the label field to take up 40% of the panel and the entry field to take up 60%. I'll
implement a simple layout manager here, both to show you how easy it is and to give you a
useful class for making panels like the one shown.
Search WWH ::




Custom Search