Java Reference
In-Depth Information
CHAPTER 10
■ ■ ■
Layout Managers
I n Chapter 9, you learned about the various pop-up and chooser classes available from the
Swing component set. In this chapter, you'll learn about the AWT and Swing layout managers.
While this topic focuses on the Swing component set, you can't use them in a vacuum. You
need to understand both the AWT and Swing layout managers. In fact, you're more apt to use
four of the five AWT layout managers than three of the five Swing layout managers. The AWT
layout managers are FlowLayout , BorderLayout , GridLayout , CardLayout , and GridBagLayout .
The Swing layouts are BoxLayout , OverlayLayout , ScrollPaneLayout , ViewportLayout , and
SpringLayout . Another manager is JRootPane.RootLayout , which was described in Chapter 8.
In addition to the layout managers, you'll look at several helper classes: GridBagLayout 's
constraint class GridBagConstraints , the SizeRequirements class used by both the BoxLayout
and OverlayLayout managers, and the SpringLayout manager's associated Spring and
SpringLayout.Constraints classes.
Layout Manager Responsibilities
Every container, such as a JPanel or Container , has a layout manager. That layout manager is
responsible for positioning components, regardless of the platform or screen size.
Layout managers eliminate the need to compute component placement on your own,
which would be a losing proposition, since the size required for any component depends on
the platform on which your program is deployed and the current look and feel. Even for a
simple layout, the code required to discover component sizes and compute absolute positions
could be hundreds of lines, particularly if you concern yourself with what happens when the
user resizes a window. A layout manager takes care of this for you. It asks each component in
the container how much space it requires, and then arranges the components on the screen as
best it can, based on the component sizes on the platform in use, the available space, and the
rules of the layout manager.
To find out how much space a component needs, the layout manager calls the component's
getMinimumSize() , getPreferredSize() , and getMaximumSize() methods. These methods report
the minimum, preferred, and maximum space that a component requires to be displayed
correctly. Thus, each component must know its space requirements. The layout manager then
uses the component's space requirements to resize components and arrange them on the
screen. Your Java program never needs to worry about platform-dependent positioning, beyond
layout manager setup.
343
Search WWH ::




Custom Search