How to work with JCheckBox with Image

How can I have a ceckbox grup with image?

I use:

for (String testata : listaTestate) {
        JCheckBox checkbox = new JCheckBox();
        ImageIcon imgTestata = new ImageIcon("src/img/"+testata+".png");
        checkbox.setName(testata);
        checkbox.setBackground(new Color(194, 169, 221));
        checkbox.setSelected(true);
        testate.add(checkbox);
        JLabel label = new JLabel(imgTestata);
        label.setBackground(new Color(194, 169, 221));
        label.setPreferredSize(new Dimension(500, 50));
        testate.add(label);
    }

but a lot of space between the ImageIcon and the JCheckBox

Last updated:2/4/2015 10:45:16 PM

1 Answers

Anonymous User
Anonymous User

Without knowing the layout manager, it's difficult to be 100%, but if I was doing this, I might use a GridBagLayout...

testate.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridy = 0;
gbc.insets = new Insets(4, 4, 4, 4);
gbc.anchor = GridBagConstraints.WEST;
for (String testata : listaTestate) {
    gbc.gridx = 0;
    JCheckBox checkbox= new JCheckBox();
    ImageIcon imgTestata = new ImageIcon(getClass().getResource("/img/"+testata+".png"));
    checkbox.setName(testata);
    checkbox.setBackground(new Color(194, 169, 221));
    checkbox.setSelected(true);
    testate.add(checkbox,gbc);
    gbc.gridx++;
    JLabel label = new JLabel(imgTestata);
    label.setBackground(new Color(194, 169, 221));
    testate.add(label,gbc);
    gbc.gridy++;
}

Answer