Search code examples
javaswinglayout-managergridbaglayout

GridBagLayout does not display a component


I wrote a component to display a circular progressbar. When I put it in BorderLayout everything looks fine.

But it can't be seen when a GridBagLayout is set.

    p.setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = 0;
    p.add(north(), gbc);
    gbc.gridx = 0;
    gbc.gridy = 1;
    p.add(west(), gbc);
    gbc.gridx = 1;
    gbc.gridy = 1;
    p.add(bar, gbc);

I have no idea whether it is the problem of setting the GridBagConstraints or other reasons.


Solution

  • But it can't be seen when a GridBagLayout is set.

    Probably because you didn't override the getPreferredSize() method of your component so the preferred size will be (0, 0).

    The GridBagLayout will attempt to display the component at its preferred size.

    I would guess you would need to use the fill constraint when adding the component so it can be automatically resized to fill the space available in the cell. Read the section from the Swing tutorial on How to Use GridBagLayout for more information and examples.

    When I put it in BorderLayout everything looks fine.

    When added to the CENTER of a BorderLayout the component will be resized to fill the space available.