Title: Professional Java Programming
ISBN: 186100382x
US Price: $ 59.99
Canadian Price:
C$ 89.95
UK Price: £ 45.99
© Wrox Press Limited, US and UK.

Reviews : Java Books :
Professional Java Programming : Using Layout Managers

fill

By default, a component's size is set to either its preferred or minimum size, regardless of the size of the cell or cells that are reserved for it. At the beginning of this section on GridBagLayout, we saw a JLabel in a column that was much wider than the label's preferred width, so the label only occupied a small portion of its available display area. However, you can use the fill constraint to indicate that the component should be stretched to fill its available display area horizontally, vertically, or both. For example, the following code creates three buttons, and the first two are displayed using their preferred sizes. However, the third button is made to expand horizontally to fill the width of its column:

import java.awt.*;
import javax.swing.*;

public class Fill {

  public static void main(String[] args) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container pane = f.getContentPane();
    pane.setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = GridBagConstraints.RELATIVE;
    pane.add(new JButton("This button's preferred width "
      + "is large because its text is long"), gbc);
    pane.add(new JButton("Small centered button"), gbc);
    gbc.fill = GridBagConstraints.HORIZONTAL;
    pane.add(new JButton("Expands to fill column width"), gbc);
    f.setSize(400, 300);
  f.setVisible(true);
  }
}

The display produced by this example is as follows:

There are four constants definedin GridBagConstraints that you can use to set the fill value: