import javax.swing.*; import java.awt.*; import static java.awt.GridBagConstraints.BOTH; public class GridBagLayoutExample { public static void main(String[] args) { JFrame frame = new JFrame(); // GridBagLayout is layout manager which will place components // in grid (table) GridBagLayout layoutManager = new GridBagLayout(); // Set the layout manager for the container // The same method works also for JPanel frame.setLayout(layoutManager); // GridBagConstraints defines how the component will be positioned // in the container. The components will be placed in grid (table). GridBagConstraints c = new GridBagConstraints(); c.weighty = 1; // How to distribute extra vertical space c.weightx = 1; // How to distribute extra horizontal space c.fill = BOTH; // When the container is being resized, resize // both width and height of this component c.gridy = 0; // The component will be placed in first row c.gridwidth = 4; // The component will occupy four cells horizontally frame.add(new JTextField(), c); c.gridwidth = 1; c.gridy = 1; frame.add(new JButton("1"), c); frame.add(new JButton("2"), c); frame.add(new JButton("3"), c); frame.add(new JButton("4"), c); c.gridy = 2; frame.add(new JButton("5"), c); frame.add(new JButton("6"), c); frame.add(new JButton("7"), c); frame.add(new JButton("8"), c); frame.pack(); frame.setVisible(true); } }