HOW TO WORK WITH JCHECKBOX WITH IMAGE

Chris S

Total Post:48

Points:336
Posted by  Chris S
Java  Swing 
 987  View(s)
Ratings:
Rate this:

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

  1. Andrew Watson

    Post:39

    Points:273
    Re: How to work with JCheckBox with Image

    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

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!