Search code examples
javajpanelgridbaglayout

How do I put space between my objects using GridBagLayout?


I'm creating an application whereas I'm trying to put some distance between two text fields using GridBagLayout, but they keep appearing right underneath each other, even when I set the gridy variable to something greater than the previous text field.

I'm doing this within a panel, and on my main method, I'm calling the panel at the click of a button to display the panel on my main panel.

Here's my code for the addPanel method:

    c.weightx = 0.5;
    c.weighty = 0.5;
    c.gridx = 0;
    c.gridy = 0;
    secondPanel.add(textField1, c);
    c.weightx = 0.5;
    c.gridx = 0;
    c.gridy = 30;
    secondPanel.add(textField2, c);

And on my main method:

    c.weightx = 1.0;
    c.weighty = 1.0;
    c.insets = new Insets(6, 6, 6, 6);
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 0;
    c.gridy = 0;
    c.anchor = GridBagConstraints.FIRST_LINE_START;
    firstPanel.add(addPanel.getSecondPanel(), c);

After all this, the second text field remains right underneath the first one - even when i have specified c.gridy = 30.

My question is, how can I put some space between my two text fields using GridBagConstraints/Layout?

Any help is greatly appreciated, thank you.


Solution

  • Try specifying some insets when adding your text fields to secondPanel:

    c.insets = new Insets(5,5,5,5);
    c.weightx = 0.5;
    c.weighty = 0.5;
    c.gridx = 0;
    c.gridy = 0;
    secondPanel.add(textField1, c);
    c.weightx = 0.5;
    c.gridx = 0;
    c.gridy = 30;
    secondPanel.add(textField2, c);