img
Here is sample output from the TextAreaDemo applet:
Understanding Layout Managers
All of the components that we have shown so far have been positioned by the default layout
manager. As we mentioned at the beginning of this chapter, a layout manager automatically
arranges your controls within a window by using some type of algorithm. If you have
programmed for other GUI environments, such as Windows, then you are accustomed to
laying out your controls by hand. While it is possible to lay out Java controls by hand, too,
you generally won't want to, for two main reasons. First, it is very tedious to manually lay
out a large number of components. Second, sometimes the width and height information is not
yet available when you need to arrange some control, because the native toolkit components
haven't been realized. This is a chicken-and-egg situation; it is pretty confusing to figure out
when it is okay to use the size of a given component to position it relative to another.
Each Container object has a layout manager associated with it. A layout manager is an
instance of any class that implements the LayoutManager interface. The layout manager is
set by the setLayout( ) method. If no call to setLayout( ) is made, then the default layout
manager is used. Whenever a container is resized (or sized for the first time), the layout
manager is used to position each of the components within it.
The setLayout( ) method has the following general form:
void setLayout(LayoutManager layoutObj)
Here, layoutObj is a reference to the desired layout manager. If you wish to disable the layout
manager and position components manually, pass null for layoutObj. If you do this, you will
need to determine the shape and position of each component manually, using the setBounds( )
method defined by Component. Normally, you will want to use a layout manager.
Each layout manager keeps track of a list of components that are stored by their names.
The layout manager is notified each time you add a component to a container. Whenever the
container needs to be resized, the layout manager is consulted via its minimumLayoutSize( )
and preferredLayoutSize( ) methods. Each component that is being managed by a layout
manager contains the getPreferredSize( ) and getMinimumSize( ) methods. These return
the preferred and minimum size required to display each component. The layout manager
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home