GridBagLayout Example
The layout manager GridBagLayout provides great flexibility in laying out its components, but it can be complex to use. This GridBagLayout example demonstrates how it can be used to create a form.
// GridBagLayout Example
import java.awt.*;
import javax.swing.*;
class GridBagLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame();
Container cp = frame.getContentPane();
cp.setLayout(new GridBagLayout());
String[] fieldNames = {
"Last name","Forenames","Country","Email Address",
"Land Line","Mobile/Cell Phone"
};
int[] fieldWidths = {20,20,30,30,15,15};
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.CENTER;
gbc.insets = new Insets(20,0,15,0);
cp.add(new JLabel("Personal Information Form"),gbc);
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(5,10,5,5);
for(int i=0;i<fieldNames.length;++i) {
gbc.gridwidth = GridBagConstraints.RELATIVE;
cp.add(new JLabel(fieldNames[i]),gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
cp.add(new JTextField(fieldWidths[i]),gbc);
}
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
