Search code examples
javaswingjlabel

JLabel and JCheckBox change space between them


I created a checkbox and a label and I would like to reduce the space between them.

panoSaison = new JPanel();
        panoSaison.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), 
                "Saison des pneus recherchés", TitledBorder.LEADING, TitledBorder.TOP, null, null));
        contentPane.add(panoSaison, BorderLayout.AFTER_LAST_LINE);
        gestSaison = new GridLayout(1,2,0,0);
        panoSaison.setLayout(gestSaison);

        hiver = new JLabel();
        hiver.setText("Hiver");
        ete = new JLabel();
        ete.setText("Été");
        boxHiver = new JCheckBox();
        boxEte = new JCheckBox();

        grpSaison = new ButtonGroup();
        grpSaison.add(boxHiver);
        grpSaison.add(boxEte);

        panoSaison.add(boxHiver);
        panoSaison.add(hiver);
        panoSaison.add(boxEte);
        panoSaison.add(ete);

}

Which code should I use to fix the size?

Thank you,


Solution

  • Don't use a GridLayout. A GridLayout makes each cell the same size.

    Instead maybe you want to use a GridBagLayout. Then each cell will be the size of the largest cell in the column.

    Read the section from the Swing tutorial on How to Use GridBagLayout for more information and working examples. The example shows how to add a component to a given cell. So you will basically need to create your own 2x2 grid and add each of the components to a particular cell in the grid.

    The tutorial explains the basics of all the standard layout managers.