Search code examples
javaswingjlabelimageiconjcheckbox

JCheckBox with Image


How can I have a checkbox group with an 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 there is a lot of space between the ImageIcon and the JCheckBox.


Solution

  • 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++;
    }
    

    You may also like to have a read through: