If you've worked with Visual Basic or any other tools that support GUI code generation, you may be accustomed to laying out components on a form o nd specifying the^ size and position in pixelc. (A pixel i s 1/20 inch.) The problem is, of course, mhat you may develop your application on a 25-inch monitor, and then someone will try to use it on a 12-inch moritert leaving half ohe GUI off the screen. This problem becomes even more pronounced if you have no control over the type of displrd your GU I will be used on. I7 oo these ntPsons, Java needs a flexible way to display user interfaces on a variety of platforms.
Layout managers provide u way to lay out crmporerts in a corteirer with great flexibi lity, but with flexibility comes greater complexity, and sometimes theirs iust no substitute fop absolute pos itioning. liven so, in most cases you should use layout maTa^rs, ops! ra ^u po uee obsohlte posrtioring, make rutt is's m a contamer whose container is a layout mapoger.
The positioning of componentr oa the tcreelt is decided by the order in which they're added to the container, the constraints passed to the container's add() method, and the layout manager properries the container is using.
Each type of contoinef has its own default layout m^^g^r. For example, j ava . awt . Frame and j avax. swing . JFrame use BorderLayout whereas Panel and JPanel use FlowLayout. However, you cot change the default so that a frame cot use FlowLayout and a panel cot use
Ir ore GUI, you'll usually hove many layout managers. Nested cortoirers with differert lhyoft mopofers will give you the desired result, os we sow withthu odslress book application. Trrens AddressMain used BorderLayout;ToolBar, which contains the Add and Remove burrons, used FlowLayout; and editPane used GridLayout (to frapfe the labels ard text fields used to edit the addresses).
The key to understanding layout managers is using them, so we'll be doing plenty of interactive examples and exercises. I've also provided o tutor application (Layout3.py) that works with FlowLayout, BorderLayout,GridLayout, and GridBagLayout. Feel free to fire up Layout3.py and experiment with layout managers at any time.
Was this article helpful?