Java Reference
In-Depth Information
(where possible). With
GridBagLayout
, elements can have different sizes and can occupy
multiple rows or columns.
There is only the no-argument constructor for
GridBagLayout
:
public GridBagLayout()
The position and behavior of each element is specified by an instance of the
GridBagConstraints
class. By properly constraining the elements, you can specify the number
of rows and columns a component occupies, which component grows when additional screen
real estate is available, and various other restrictions. The actual grid size is based on the
number of components within the
GridBagLayout
and the
GridBagConstraints
of those objects.
For example, Figure 10-5 shows a
GridBagLayout
with seven components, arranged in a 3×3 grid.
Figure 10-5.
GridBagLayout with seven components in a 3×3 grid
■
Note
The maximum capacity of a screen using
GridBagLayout
is 512 rows by 512 columns. This is
specified by the protected
MAXGRIDSIZE
constant of the layout manager.
The code used to create Figure 10-5 is shown in Listing 10-1.
Listing 10-1.
Seven-Button GridBagLayout
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
public class GridBagButtons {
private static final Insets insets = new Insets(0,0,0,0);
public static void main(final String args[]) {
Runnable runner = new Runnable() {
public void run() {
final JFrame frame = new JFrame("GridBagLayout");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
JButton button;