An example of how you could achieve a demonstrated layout using a GridBagLayout :
class Main extends JFrame implements Runnable { JLabel lblIpAddress = new JLabel(); JLabel lblSubnet = new JLabel(); JLabel lblGateway = new JLabel(); JTextField txtIpAddress = new JTextField(); JTextField txtSubnet = new JTextField(); JTextField txtGateway = new JTextField(); public void run() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container content = this.getContentPane(); lblIpAddress.setText("IP Address"); lblIpAddress.setLabelFor(txtIpAddress); lblSubnet.setText("Subnet"); lblSubnet.setLabelFor(txtSubnet); lblGateway.setText("Gateway"); lblGateway.setLabelFor(txtGateway); GridBagLayout layout = new GridBagLayout(); content.setLayout(layout); content.add(lblIpAddress, newLabelConstraints()); content.add(txtIpAddress, newTextFieldConstraints()); content.add(lblSubnet, newLabelConstraints()); content.add(txtSubnet, newTextFieldConstraints()); content.add(lblGateway, newLabelConstraints()); content.add(txtGateway, newTextFieldConstraints());
The main drawback is that if you want to say, add the right-aligned row of buttons (for example: "OK" and "Cancel") at the bottom, where the buttons do not match anything else, you'd need to use a nested JPanel. (Or do something like a form that has a separate column for each button, and then the text field fields cover all of these columns and an extra separation column. This is pretty inconsistent, and it will negatively affect readability. I believe MiGLayout that is the third-party layout manager can handle this situation accurately, because since it allows you to group / overlap grid cells and split the merged cell.)
source share