Search code examples
javaswinglayout-managergridbaglayout

Layout problems - Java


I am using GridBagLayout in a project I've been working on, the problem is that when I compile in my computer or in others at my uni it shows properly how I want it to be.

Proper way

But when I run it on a different PC it is displayed different, the top-left panel and the radar panel are not like they should be.

Wrong way

We both have the same JDK and use NetBeans 7.3, so I don't know where the problem is.

This is the method I am using to add the panels to the frame.

private void agregarPaneles() {

    this.setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.insets = new Insets(10, 10, 10, 10);
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.gridwidth = 1;
    gbc.gridheight = 1;
    add(scrollerVuelos, gbc);
    gbc.gridx = 1;
    gbc.gridy = 0;
    gbc.gridwidth = 1;
    gbc.gridheight = 1;
    add(panelEstado, gbc);
    gbc.gridx = 2;
    gbc.gridy = 0;
    gbc.gridwidth = 1;
    gbc.gridheight = 1;
    add(panelOrdenes, gbc);
    gbc.gridx = 0;
    gbc.gridy = 1;
    gbc.gridwidth = 3;
    gbc.gridheight = 1;
    add(panelRadar, gbc);

}

Solution

  • The code you posted in not enough to give you an exact answer, but in general:

    If GridBagLayout doesn't have enough space to display a component at its preferred size it will then use the minimum size of the component. Since many components have a small minimum size the component can get shrunk to almost nothing.

    So you may need to look at setting minimum sizes on your panels. You can also look at the weightX and weighty values as they have an impact on how a component is resized.

    Read the Swing tutorial on How to Use GridBagLayout for more information and examples.

    Also remember you can use nested panels with different layout managers if that makes the layout easier. For example maybe the main layout should be a BorderLayout. Then in the NORTH you add a panel using a GridLayout. In the CENTER you add your other panel.