Java Reference
In-Depth Information
Grid-bag layout
17
We present the most powerful but also the most complicated layout manager of
Java, the grid-bag layout. This layout manager allows us to design complex arrange-
ments of components without using stacks of nested intermediate components.
The grid layout described in Chapter 2 allows a component to be embedded in
one cell of the grid and all cells have the same size. The grid-bag layout discussed
here allows different widths or heights for different columns and rows. In addition,
a component can be embedded to cover more than one cell. These cells then form
a bag , i.e. a rectangular sub-grid.
When using grid-bag layout, the components are not placed according to the
order of the add commands. The placement is done by passing to the layout man-
ager information on the position of every component and on the size of the bag it
has to be embedded into.
The grid-bag layout is a bit tricky to use. Many beginners give up using this
very powerful tool after a few tries because 'it does not do what it is told to do'.
We first discuss and analyse these problems and then show how to solve them.
Only then do we turn to describing the Java classes involved in realizing a grid bag
layout.
The example layout is specified in Figure 17.1. The layout consists of six panels
that are embedded into a parent component, e.g. the content pane of frame. As a
first step we determine the size of the grid, i.e. the number of rows and columns.
Here a 4
4 grid seems appropriate. The grid is indicated by dashed lines in
Figure 17.1. The columns and rows are numbered from left to right and from top
to bottom, both starting with zero. The grid structure, i.e. the number of rows and
×
!
columns, is not explicitly specified by the programmer. Instead the programmer
specifies the size and location of the embedded components. The layout manager
then computes the necessary grid structure. This computation is, however, not
always done in the way we expect, as we shall shortly see.
The size of a component is specified as the number of columns and rows it
spans. In Figure 17.1 panel A spans two columns and three rows and panel D spans
one column and two rows. The location of a component is specified by the left-
most column and top-most row it covers. In Figure 17.1 panel A is located at (0
,
0)
and B is at (2
0). Table 17.1 summarizes the parameters for the six panels. In
the next section we describe how these values are passed to the layout manager.
,
Search WWH ::




Custom Search