Search code examples
javaswinglayoutmiglayoutgaps-in-visuals

How to remove vertical gap between two cells in MigLayout?


Very simple question: How can I remove the vertical gap between the two cells containing the two JCheckBox? I have marked the gap in the picture with a red border.

gap

And here is the code:

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

import net.miginfocom.swing.MigLayout;

public class Main {
    public static void main(String[] args) {
        JPanel somePanel = new JPanel();
        somePanel.setLayout(new MigLayout("insets 0, debug", "", ""));
        somePanel.add(new JCheckBox("first option"), "h 20!");
        somePanel.add(new JButton("click me"), "spany 2, h 40!, w 60%, wrap");
        somePanel.add(new JCheckBox("option two"), "h 20!");

        JFrame frame = new JFrame();
        frame.setContentPane(somePanel);
        frame.pack();
        frame.setVisible(true);
    }
}

Solution

  • Minimum gaps are defined in either in the row/column constraints if they should be applied between particular rows/columns only:

    new MigLayout("insets 0, debug", "", "[]0[]"));
    

    (wondering a bit that this didn't work for you? It's fine here :)

    or in the layoutContraints if they should be applied between all rows:

    new MigLayout("insets 0, gapy 0, debug"));
    

    BTW: layout "coding" should follow the same rules as all coding, f.i. DRY :-) In particular, my rule is to not repeat component constraints if you can achieve the goal with layout/row constraints. In the example you can get rid of all component constraints except the spanning by:

    somePanel.setLayout(new MigLayout("insets 0, debug, wrap 2", 
            "[][60%, fill]", "[20!, fill]0"));
    somePanel.add(new JCheckBox("first option"));
    somePanel.add(new JButton("click me"), "spany 2");
    somePanel.add(new JCheckBox("option two"));