Sooner or later, the Sun-supplied layout managers are going to stop short of what you need. Or, if you're like me, you'll think that maybe a GridBagLayout would work but you just don't want to plow through that opaque morass. There's an alternative: create your own layout manager. It's easier than you might think, once you've mastered the tricky LayoutManager interface. Fortunately, that's mostly a matter of learning what not to code.
Here's the short course: implement the layoutContainer() method and stub out the others. Trust me! Skip right ahead to The RowLayoutManager where you'll see it done in one useful example.
I'm writing this because I probably wouldn't take the above advice. I'd want to know why. OK, Here's why.
The addLayoutComponent() and removeLayoutComponent() methods look important. The important thing about these methods is that add() is not trustworthy. If you add Components with the two argument add - add( Component, Object ) - this method will be called. If you use the simple form - add( Component ) - this method will not be called. There will be Components added to your container that you'll not know about. If you don't know about them, you certainly won't be able to lay them out.
Of course, when Components are added to the Container you want to lay out, the Container itself keeps a record. When it's time to lay out the Container, your LayoutManager will have its layoutContainer( Container ) method called. That passes your LayoutManager the container reference it needs. With the Container reference you can call getComponents() to get a complete array of all the Components that have been added.
It follows that if your LayoutManager ignores addLayoutComponent() then it will also ignore removeLayoutComponent().
The minimumLayoutSize() and preferredLayoutSize() methods can be stubbed out to return any Dimension you choose. Chances are excellent that these methods will never be called. Before spending even a minute on these, try having your Container (the one you'll be laying out) return a sensible preferred size. (It could also compute its minimum and maximum sizes, but almost nothing in the AWT or Swing pays even the slightest attention.)
Now are you comfortable with stubbing out four of the five methods here? I hoped you would be.
© 2005 by Martin Rinehart