All the key gridbag-layout machinery is
exhibited in the following example, in which the repetitive part of component
placement is done in the placeComponent
method, keeping clutter
controlled:
import java.awt.*; import javax.swing.*; public class TestPanel extends JPanel { public TestPanel () { GridBagLayout gbl = new GridBagLayout(); setLayout(gbl); GridBagConstraints gbc = new GridBagConstraints(); // Fill both ways and allow expansion of all components: gbc.fill = GridBagConstraints.BOTH; gbc.weightx = 1.0; gbc.weighty = 1.0; // Place components: placeComponent(0, 0, 1, 2, "A", gbl, gbc); placeComponent(1, 0, 1, 1, "B", gbl, gbc); placeComponent(0, 2, 1, 3, "C", gbl, gbc); placeComponent(1, 1, 1, 4, "D", gbl, gbc); placeComponent(2, 0, 1, 1, "E", gbl, gbc); placeComponent(2, 1, 1, 1, "F", gbl, gbc); placeComponent(2, 2, 1, 1, "G", gbl, gbc); placeComponent(2, 3, 1, 1, "H", gbl, gbc); placeComponent(2, 4, 1, 1, "I", gbl, gbc); } // Handle placement details: public void placeComponent (int x, int y, int w, int h, String s, GridBagLayout l, GridBagConstraints c) { c.gridx = x; c.gridwidth = w; c.gridy = y; c.gridheight = h; TestButton p = new TestButton(s); l.setConstraints(p, c); add(p); } }