Setting the Stretchyness of Rows and Columns in a GridBagLayout Using Layout Weights
Column and row stretchyness is controlled by the weight of specific
columns and rows. A column with zero weight does not stretch; it is
given just enough space to accommodate the component with the widest
preferred width in that column; this also applies to a row with zero weight.
When a single column has a non-zero weight, it is
given all the excess horizontal space; it is the only column that
stretches. In this case, the value of the weight doesn't matter
When more than one column has a non-zero weight, the excess
space is distributed among the non-zero weight columns using the
weight values. In particular, if the excess space is P pixels, and
the column weights for column^i is weight^i, then column^i gets
exactly (weight^i * P) / (sum-of-all-column-weights). For example, if
column 1 has weight 1 and column 2 has weight 2 and the excess space
is 90 pixels, column 1 will get 30 extra pixels and column 2 will get
60 extra pixels. Rows with a non-zero weight behave in similar
fashion.
There are two ways to set the weight of a column or row. The
first is to set the weights using the GridBagLayout object. The
second way is to assign weights to components. The weight of a column
is determined by the maximum of all the weights of all components in
that column including the assigned weight of the column in the
GridBagLayout object. So, if the maximum
weight of all the components in the column is 2 and the weight for
that column in the GridBagLayout object is 3, the column weight is 3.
The weight of a row is determined in similar fashion.
Typically, weights are set using either method, not
both. In particular, if only one row or column needs to be stretchy,
it is usually more convenient to assign a non-zero weight to the
stretchy component. Then the right thing happens. Whereas, if two or more
columns or rows are stretchy and the weights are not the same, it is
sometimes more convenient to set the weights in the GridBadLayout
object.
This example demonstrates how to assign weights in the
GridBagLayout object. See Setting the Stretchyness of Columns and Rows in a GridBagLayout Using Component Weights
for an example of how to set weights on a component.
See Creating a GridBagLayout for an example on how to
use a gridbag layout with gridbag constraints.
GridBagLayout gbl = new GridBagLayout();
// We assume that the grid has 2 rows and 3 columns.
// The 1st column and row do not stretch.
// The 2nd column gets 1/3 of the excess horizontal space.
// The 3rd column gets 2/3 of the excess horizontal space.
// The 2nd row gets all of the excess vertical space.
gbl.columnWeights = new double[]{0.0f, 1.0f, 2.0f};
gbl.rowWeights = new double[]{0.0f, 1.0f};
Post a comment