Java Reference
In-Depth Information
ent[] getComponents()
returnsanarrayofthecontainer'scomponents,and
int
getComponentCount()
returns the number of components in the container.
Window
declaresa
void pack()
methodformakingatop-levelwindowjustlarge
enough to display all its components at their
preferred
(natural) sizes. Also,
pack()
makes the window (and any owner of the window—dialog boxes are typically owned
by other windows) displayable when not already displayable.
Window
alsodeclaresa
void setSize(int width, int height)
method
that lets you size a window to a specific size (in pixels).
Continuingfromthepreviousexample,supposeyouwanttoaddtheYesbuttontoa
panel(whichmightalsocontainaNobutton).Thefollowingexampleshowsyouhow
to accomplish this task:
Panel pnl = new Panel();
pnl.add(btnYes);
Layout Managers Overview
Containerscancontaincomponentsbutcannotlaythemoutonthescreen(e.g.,inrows,
in a grid, or in some other arrangement). Layout managers handle this task. A layout
manager is typically associated with a container to lay out the container's components.
Note
Layout managers provide a screen size-independent way to display a GUI.
Without them, an application would have to obtain the current screen size and adapt
container/componentsizestoaccountforthescreensize.Doingsocouldinvolvewrit-
ing hundreds of lines of code, a tedious proposition at best.
AWT provides several layout managers in the
java.awt
package:
BorderLay-
out
(layoutnomorethanfivecomponentsinacontainer'snorth,south,east,west,and
centerareas),
CardLayout
(treateachcontainedcomponentasacard;onlyonecard
isvisibleatatime,andthecontaineractsasastackofcards),
FlowLayout
(arrange
components in a horizontal row),
GridBagLayout
(lay out components vertically,
horizontally,oralongtheir
baseline
[lineservingasanoriginforthepurposeoflayout]
withoutrequiringthatthecomponentsbeofthesamesize),and
GridLayout
(layout
the components in a rectangular grid).
Layout manager classes implement the
java.awt.LayoutManager
interface,
which declares methods that AWT calls when a container's components need to be
laid out. You don't need to be aware of these methods unless you're planning to
create your own layout manager. If so, you'll also want to be aware of
java.awt.LayoutManager2
, a
LayoutManager
subinterface.