Search code examples
javaswinggridbaglayout

GridBagLayout - Placing multiple components below a long text field


I'm testing a simple form using GridBagLayout and having some alignment issues. I'd like to place two small fields on the row below the top "Item" row but the long text field is causing the small text field below it to not align properly.

Here is an image of what it is doing currently, I just need the small box on the second row placed next to the first price field.

enter image description here

Code:

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.*;
public class GridBagLayoutTest {

public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel panelMain = new JPanel();
    JPanel panelForm = new JPanel(new GridBagLayout());

    JLabel lblItem = new JLabel("Item: ");
    JLabel lblPrice = new JLabel("Price: ");
    JLabel lblQuantity = new JLabel("Quantity: ");

    JTextField txtItem = new JTextField(15);
    JTextField txtPricePounds = new JTextField(3);
    JTextField txtPricePence = new JTextField(2);
    JTextField txtQuantity = new JTextField(3);

    GridBagConstraints gbc = new GridBagConstraints();

    gbc.anchor = GridBagConstraints.LINE_END;
    gbc.gridx = 0;
    gbc.gridy = 0;
    panelForm.add(lblItem, gbc);

    gbc.gridx = 0;
    gbc.gridy = 1;
    panelForm.add(lblPrice, gbc);

    gbc.gridx = 0;
    gbc.gridy = 2;
    panelForm.add(lblQuantity, gbc);

    gbc.anchor = GridBagConstraints.LINE_START;
    gbc.gridx = 1;
    gbc.gridy = 0;
    panelForm.add(txtItem, gbc);

    gbc.gridx = 1;
    gbc.gridy = 1;
    panelForm.add(txtPricePounds, gbc);


    gbc.gridx = 2;
    gbc.gridy = 1;
    panelForm.add(txtPricePence, gbc);

    gbc.gridx = 1;
    gbc.gridy = 2;
    panelForm.add(txtQuantity, gbc);


    panelMain.add(panelForm);

    frame.add(panelMain);
    frame.setSize(400, 200);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

}

Solution

  • Remember, GridBagLayout is still a grid based layout management system. It is also very flexible. One of the features it provides is the ability to configure how many columns or rows a component might span.

    So, if we can modify your code and add gridwidth to allow the txtItem to span 2 columns and the remaining fields to span 1;

    gbc.anchor = GridBagConstraints.LINE_START;
    gbc.gridx = 1;
    gbc.gridy = 0;
    gbc.gridwidth = 2;
    add(txtItem, gbc);
    
    gbc.gridwidth = 1;
    gbc.gridx = 1;
    gbc.gridy = 1;
    add(txtPricePounds, gbc);
    

    you end up with something like...

    GridBagLayout

    Have a look at How to use GridBagLayout for more details