Listing 1: TableLayout versus GridBagLayout Code
if (useTableLayout) {
loginForm.setLayout(new TableLayout(0, 2, false, false));
loginForm.add(useridLabel, alignStr);
loginForm.add(userField);
loginForm.add(passwordLabel, alignStr);
loginForm.add(passwordField);
loginForm.add(TableLayout.getFillerComponent());
loginForm.add(rememberPasswordCB);
} else {
GridBagLayout layout = new GridBagLayout();
loginForm.setLayout(layout);
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.WEST;
c.insets = new Insets(VGAP / 2, HGAP, (VGAP / 2) + 1, 0);
c.fill = GridBagConstraints.NONE;
loginForm.add(useridLabel, c);
c.weightx = 1;
c.gridwidth = GridBagConstraints.REMAINDER;
loginForm.add(userField, c);
c.weightx = 0;
c.gridwidth = 1;
loginForm.add(passwordLabel, c);
c.gridwidth = GridBagConstraints.REMAINDER;
c.weightx = 1;
loginForm.add(passwordField, c);
c.gridx = 1;
loginForm.add(rememberPasswordCB, c);
}
Listing 2: TableLayout Demo button layout code
testPanel = new JPanel(testPanelLayout = new TableLayout(0, 3, false, false));
testPanel.add(new JButton("1, 1"));
testPanel.add(new JButton("1, 2"));
testPanel.add(new JButton("1, 3"), "align=center");
testPanel.add(new JButton("2, 1"));
testPanel.add(new JButton("2, 2"));
testPanel.add(new JButton("2, 3"), "align=right");
testPanel.add(new JButton("3, 1"));
testPanel.add(new JButton("3, 2"), "vAlign=bottom");
testPanel.add(new JButton("3, 3"), "vAlign=fill");
Listing 3: Complex TableLayout code
setLayout(new TableLayout(4, 4));
add(new JButton(" 1 [0, 0] "), "rowspan=3,vAlign=fill");
add(new JButton(" 2 [1, 0] "));
add(new JButton(" 3 [2, 0] "));
add(new JButton(" 4 [3, 0] "), "align=left");
add(new JButton(" 5 [1, 1] "), "colspan=2");
add(new JButton(" 6 [3, 1] "), "rowspan=3, align=left, vAlign=fill");
add(new JButton(" 7 [1, 2] "), "rowspan=2, valign=fill");
add(new JButton(" 8 [2, 2] "));
add(new JButton(" 9 [0, 3] "), "vAlign=top");
add(new JButton(" 10 [2, 3] "), "vAlign=top");
Listing 4: Single-column FormsPanel
FormsPanel panel = new FormsPanel(1);
panel.addSeparator("Propeller Shaft");
panel.addRow("R [cm]", new JTextField(14));
panel.addRow("D [mm]", new JTextField(14));
panel.addRow("PTI [kW]", new JTextField(14));
panel.addRow("da [mm]", new JTextField(14));
panel.addSeparator("Intermediate Shaft");
panel.addRow("ds [mm]", new JTextField(14));
panel.addRow("kl [cm]", new JTextField(14));
panel.addRow("Weight [Kg]", new JTextField(14));