Search code examples
javaswinglayout-managermiglayout

[Miglayout]adjust the size of the container to fit the total size of all components contained, with insets and gap


How can I use MigLayout so that after pack() I can see a JFrame with a proper size to hold all its children components, with borders, insets and gaps?? Now I see some elements cut off, leaving half of the size visible but half cut off.


Solution

  • I just figured out how to guarantee the proper size of a Container according to the sum of size of all the contained components without hardcoding anything.

    1. Create a JPanel panel as your working panel, instead of touching the contentPane. Just add it back to the contentPane. Don't touch the contentPane, it is the key.

    2. Set the layout of panel without hardcoded row height, column width, etc. This may ruin the layout, because your hardcoded height may be lesser or more of it is needed, leaving some line with wrong size, and leave your last line/column half cut off.

    3. Add your elements into panel. When adding them you can specify sizes.

    4. Add panel back to contentPane: getContentPane().add(panel); We don't need to set the layout of contentPane.

    5. At last, pack(), setVisible(true) as you wish. No need to setSize(), setBounds(), etc. The insets and gaps will be handled automatically by MigLayout. Viola!

    A SSCCE:

    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    
    import net.miginfocom.swing.MigLayout;
    
    public class InsetsAndBorder extends JFrame {
        public InsetsAndBorder() {
            begin();
        }
    
        private void begin() {
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            JPanel panel = new JPanel();
            panel.setLayout(new MigLayout("insets 2 2 2 2, fillx, debug", "3[]3[]3[]3", "5[]5[]5[]5"));
    
            JLabel label1 = new JLabel("1");
            JLabel label2 = new JLabel("2");
    
            JButton button = new JButton("No way!");
    
            panel.add(label1, "cell 1 2, grow");
    
            panel.add(label2, "cell 2 2, grow");
    
            panel.add(button, "cell 0 1, grow");
    
            getContentPane().add(panel);
            pack();
            setLocationRelativeTo(null);
            setVisible(true);
        }
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    InsetsAndBorder frame = new InsetsAndBorder();
    
                }
    
            });
        }
    }