Use GridBagLayout to arrange labels and fields in rows and columns. You can give each component its own position and decide how it should resize.
In this example, the labels stay on the left while the text fields on the right grow wider when you resize the window.
Source code
Save the following code as GridBagLayoutExample.java:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class GridBagLayoutExample {
void main() {
SwingUtilities.invokeLater(this::showWindow);
}
private void showWindow() {
JPanel form = new JPanel(new GridBagLayout());
addRow(form, 0, "Name:");
addRow(form, 1, "Email:");
JFrame frame = new JFrame("Contact Form");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(form);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void addRow(JPanel form, int row, String labelText) {
JLabel label = new JLabel(labelText);
JTextField field = new JTextField(20);
label.setLabelFor(field);
GridBagConstraints labelConstraints = new GridBagConstraints();
labelConstraints.gridx = 0;
labelConstraints.gridy = row;
labelConstraints.anchor = GridBagConstraints.LINE_START;
labelConstraints.insets = new Insets(6, 8, 6, 8);
form.add(label, labelConstraints);
GridBagConstraints fieldConstraints = new GridBagConstraints();
fieldConstraints.gridx = 1;
fieldConstraints.gridy = row;
fieldConstraints.weightx = 1.0;
fieldConstraints.fill = GridBagConstraints.HORIZONTAL;
fieldConstraints.insets = new Insets(6, 8, 6, 8);
form.add(field, fieldConstraints);
}
}
What the form looks like

Explanation
GridBagLayout places components in an invisible grid. Each call to form.add() passes a component and a GridBagConstraints object that tells Swing how to place it.
| Setting | What it does in this example |
|---|---|
gridx |
Selects the column: 0 for labels and 1 for fields |
gridy |
Selects the row: 0 for Name and 1 for Email |
anchor |
Aligns the label at the start of its cell |
insets |
Adds space outside each component, in top, left, bottom, right order |
weightx |
Gives the field column the extra horizontal space |
fill |
Lets each field stretch horizontally to use that space |
weightx and fill do different jobs. weightx determines which column receives extra width. fill determines whether a component grows to use the width of its cell. Without HORIZONTAL fill, the field could stay at its preferred width even when its column grows.
frame.pack() sizes the window to fit the form at its preferred size. The whole window is created on Swing’s event dispatch thread using invokeLater().
Run the example
javac GridBagLayoutExample.java
java GridBagLayoutExample
The Contact Form window opens with two rows. Drag the right edge outward to see both text fields widen while the labels stay aligned.