### Custom layouts

Occasionally you may need to write your own custom Layout class. This is most appropriate when you have a complex layout that is used in many different places in your application. It may be appropriate when you can optimize layout using application specific knowledge. Before building a custom layout you should consider the following:

- Can the layout be achieved with an existing layout such as GridLayout or by nesting several different layouts?
- Can the layout be isolated into a common resize listener?
- Are you defining a general layout algorithm with programmer supplied configuration parameters or just positioning widgets specifically for your application?

Unless you are writing a very generic layout that will be used by several Composite widgets, it is often simpler and easier to calculate sizes and position children in a resize listener. Many of the SWT custom widgets were written this way. Although a new widget can be implemented as a Composite/Layout pair, implementing it as a Composite that does its layout in a resize listener and computes its preferred size in computeSize(...) is clearer, and does not require the writing of an extra class.

If you still believe that you need a custom layout class then it is a good idea to first implement the layout algorithm in a resize listener. This makes for simpler debugging of the algorithm itself. Be sure to test the various cases for layout, which are resizing smaller, resizing larger, wrapping, and clipping. Once you have the algorithm working, the code can be refactored into a subclass of Layout.

Layouts are responsible for implementing two methods:

- computeSize(...) calculates the width and height of a rectangle that encloses all of the composite's children once they have been sized and placed according to the layout algorithm. The hint parameters allow the width and/or height to be constrained. For example, a layout may choose to grow in one dimension if constrained in another.
- layout(...) positions and sizes the composite's children. A layout can choose to cache layout-related information, such as the preferred extent of each of the children. The flushCache parameter tells the Layout to flush cached data, which is necessary when other factors besides the size of the composite have changed, such as the creation of removal of children, or a change in the widget's font.

Further discussion of custom layouts can be found in Understanding layouts in SWT.