Java Reference
In-Depth Information
Setting up grid bag constraints requires a lot of repetitive code. To save some typing, the
email panel's class has a method to set a component's constraints and add it to the panel:
private void addComponent(Component component, int gridx, int gridy,
int gridwidth, int gridheight, int weightx, int weighty, int fill,
int anchor) {
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = gridx;
constraints.gridy = gridy;
constraints.gridwidth = gridwidth;
constraints.gridheight = gridheight;
constraints.weightx = weightx;
constraints.weighty = weighty;
constraints.fill = fill;
constraints.anchor = anchor;
gridbag.setConstraints(component, constraints);
add(component);
}
This method could be used in any panel class that uses a GridBagLayout manager stored
in an instance variable named gridbag . It doesn't use the insets , ipadx , and ipady vari-
ables of the GridBagConstraints class, so they retain their default values.
The following statements call this addComponent() method to add a Subject label and
text field to the panel:
JLabel subjectLabel = new JLabel(“Subject: “);
addComponent(subjectLabel, 0, 1, 1, 1, 10, 100, GridBagConstraints.NONE,
GridBagConstraints.EAST);
JTextField subject = new JTextField();
addComponent(subject, 1, 1, 9, 1, 90, 100, GridBagConstraints.HORIZONTAL,
GridBagConstraints.WEST);
The panel is completed with statements to add CC and BCC labels and fields:
// add a CC label at (0,2) 1 cell wide
JLabel ccLabel = new JLabel(“CC: “);
addComponent(ccLabel, 0, 2, 1, 1, 10, 100, GridBagConstraints.NONE,
GridBagConstraints.EAST);
// add a CC text field at (1,2) 4 cells wide
JTextField cc = new JTextField();
addComponent(cc, 1, 2, 4, 1, 40, 100, GridBagConstraints.HORIZONTAL,
GridBagConstraints.WEST);
// add a BCC label at (5,2) 4 cells wide
JLabel bccLabel = new JLabel(“BCC: “);
addComponent(bccLabel, 5, 2, 1, 1, 10, 100, GridBagConstraints.NONE,
GridBagConstraints.EAST);
// add a BCC text field at (6,2) 4 cells wide
Search WWH ::




Custom Search