Note that when using the BorderLayout, you must add components with either the add(String, Component) or the add(Component, Object) method to ensure the components are all added correctly. A common mistake people make is to use add(Component), which can result in some of the components not being visible.
"JavaRanch, where the deer and the Certified play" - David O'Meara
Well I was poking around in another book last night (Java Algorithms by Scott Robert Ladd) I think I found the right answer
Basically, Containers keep track of the Components they contain but it is the LayoutManager that actually handles the positioning of the Components. Each Container can be associated with only one LayoutManager or have a null LayoutManager which means you have to supply the code to handle positioning and resizing separately.
LayoutManagers contain a number of methods: addLayoutComponent(), layoutContainer(), etc. However, in most situations you don't call these directly. Instead, you use the Container methods which in turn call the LayoutManager methods ie Container.add() calls LayoutManager addLayoutComponent().
The key to the difference between LayoutManagers which require constraints such as BorderLayout, and those which don't have constraints such as FlowLayout is this:
Classes implementing LayoutManager2 ie BorderLayout, CardLayout and GridBagLayout maintain an internal list of their components.
Classes implementing LayoutManager ie FlowLayout, GridLayout query the target container for a list of Components
This is why we see the behaviour shown in the original example. When components are added to a Container, the Container itself keeps a list of the objects. If, for example, the Layout has been set to FlowLayout, and the Container is resized, the FlowLayout manager will get a list of the component objects associated with the Container and then perform the size and position functions.
If the Layout is then changed to, for example, BorderLayout, and the Container is resized, no request is made to the Container for a list of the associated Components. The BorderLayout contract states it will keep it's own list of Components; as far as it's concerned, it has no components and nothing needs to be positioned.
This is why the Components need to be re-added to the Container.
Hope thats clearer.
Jane
Jane Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport
Won't you be my neighbor? - Fred Rogers. tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
|