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:
HORIZONTAL
Expand the component horizontally to fill its display area
VERTICAL
Expand the component vertically to fill its display area
BOTH
Expand the component both horizontally and vertically to fill its display area
NONE
The component should be allowed to remain at its natural (preferred or minimum) size; this is
the default value
New on the Java Boutique:
New Review:
Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling
API boasts simplicity, ease-of-integration, a well-rounded feature
set, and it's free!
New Applet:
Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA
sequences into three useful formats.
Elsewhere on internet.com:
WebDeveloper Java
Lots of Java information on webdeveloper.com
WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.
ScriptSearch Java
Hundreds of free Java code files to download.
jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.