11. Layout Managers
Precise layout functionality is often performed and a repetitive task. By the principles of OOP, it should be done by classes dedicated to it. These classes are layout managers.
Platform independence requires that we delegate the positioning and painting to layout managers. Even then, Java does not guarantee a button will look the same in different platforms.(w/o using Swing)
Components are added to a container using add method. A layout manager is associated with the container to handle the positioning and appearance of the components.
add method is overloaded. Constraints are used differently by different layout managers. Index can be used to add the component at a particular place. Default is -1 ( i.e. at the end)
Component add(Component comp) Component add(Component comp, int index) void add(Component comp, Object constraints) void add(Component comp, Object constraints, int index)
setLayout is used to associate a layout manager to a container. Panel class has a constructor that takes a layout manager. getLayout returns the associated layout manager.
It is recommended that the layout manager be associated with the container before any component is added. If we associate the layout manager after the components are added and the container is already made visible, the components appear as if they have been added by the previous layout manager (if none was associated before, then the default). Only subsequent operations (such as resizing) on the container use the new layout manager. But if the container was not made visible before the new layout is added, the components are re-laid out by the new layout manager.
Positioning can be done manually by passing null to setLayout.