Search code examples
javaswinglayout-managerborder-layoutgrouplayout

How can I get the size of a container gap used by GroupLayout?


I have many JPanel with GroupLayout and I use addContainerGap() to add the gap on the borders. Also I have a panel with other layout (BorderLayout) and I want to add the same gap with its container as the group layout panels (I will add it through a empty border).

So my question is, how can I get the size of a container gap? Or is it better to use another approach?

I don't find how to get the size of the container gap so the only thing I can think is adding the panel inside a panel with a group layout and add there the containers gap.


Solution

  • For BorderLayout use:

    1. new BorderLayout(hgap,vgap) - or a combination of the following two:
    2. BorderLayout.setHgap(int)
    3. BorderLayout.setVgap(int)

    Edit

    But this doesn't answer how to get the gap size used by GroupLayout..

    Look to GroupLayout.getLayoutStyle() then methods like: LayoutStyle.getPreferredGap(JComponent,JComponent,LayoutStyle.ComponentPlacement,int,Container) and of course note that the preferred gap might vary across the components of the layout.

    For example you can use the next code to get the gap size for the north border:

    LayoutStyle ls = gl.getLayoutStyle();
    
    // Can be null if not already set.
    if (ls == null) {
        // If not set, get the default style.
        ls = LayoutStyle.getInstance();
    }
    
    // What is the size of north gap if there is a JLabel?
    System.out.format("North gap: %d", ls.getContainerGap(new JLabel(), SwingConstants.NORTH, null));