Java Reference
In-Depth Information
and how a component should grow when there is more space available for it than
it needs for its default size. The anchor field specifies how a component should be
positioned when there is more space available than it uses. GridBagConstraints
defines a number of constants that are legal values for these last two fields. Finally,
weightx and weighty specify how extra horizontal and vertical space should be
distributed among the components when the container is resized. Consult refer-
ence material on GridBagConstraints for more details.
Example 10-7 shows a short program that uses a GridBagLayout layout manager to
produce the layout pictured in Figure 10-7. Note that the program reuses a single
GridBagConstraints object, which is perfectly legal.
Figure 10•7. Components laid out with a GridBagLayout
Example 10•7: GridBagLayoutPane.java
package com.davidflanagan.examples.gui;
import java.awt.*;
import javax.swing.*;
public class GridBagLayoutPane extends JPanel {
public GridBagLayoutPane() {
// Create and specify a layout manager
this.setLayout(new GridBagLayout());
// Create a constraints object, and specify some default values
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH; // components grow in both dimensions
c.insets = new Insets(5,5,5,5);
// 5-pixel margins on all sides
// Create and add a bunch of buttons, specifying different grid
// position, and size for each.
// Give the first button a resize weight of 1.0 and all others
// a weight of 0.0. The first button will get all extra space.
c.gridx = 0; c.gridy = 0; c.gridwidth = 4; c.gridheight=4;
c.weightx = c.weighty = 1.0;
this.add(new JButton("Button #1"), c);
c.gridx = 4; c.gridy = 0; c.gridwidth = 1; c.gridheight=1;
c.weightx = c.weighty = 0.0;
Search WWH ::




Custom Search