Search code examples
javaswinggridbaglayoutjcheckbox

Adjusting the space between checkboxes in java swing


I am trying to use gridbaglayout (in windowbuilder pro in Eclipse) to make a gui with checkboxes. My problem is similar to this: stackOverflow:How to reduce space between JCheckboxes in GridLayout but setting the border to empty did not help. The following code produces the following following gui:

/*===============Check Boxes====================*/
ArrayList<String> names = test();
    int size = names.size();
    JCheckBox cb[]=new JCheckBox[size]; 

    for(int i=0;i<size;i++) {
        cb[i]=new JCheckBox(names.get(i));
        cb[i].setVisible(true);
        cb[i].setBorder(BorderFactory.createEmptyBorder());

        GridBagConstraints gbc_chckbxTestpurposes = new GridBagConstraints();
        //gbc_chckbxTestpurposes.insets = new Insets(0, 0, 0, 0);
        gbc_chckbxTestpurposes.gridx = 0;
        gbc_chckbxTestpurposes.gridy = i+1;
        contentPane.add(cb[i], gbc_chckbxTestpurposes);
     }

}

gui

As you can see, the vertical spacing is quite off, as well as the horizontal spacing on the last checkmark.


Solution

  • Try to use GridBagConstraints.NORTHWEST anchor and add a filler JPanel last with fill=vertically and weighty=1