Home > DeveloperSection > Forums > How to work with JCheckBox with Image
Chris S
Chris S

Total Post:48

Points:336
Posted on    February-04-2015 10:26 PM

 OOPS Java  Swing 
Ratings:


 1 Reply(s)
 702  View(s)
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



Andrew Watson
Andrew Watson

Total Post:39

Points:273
Posted on    February-04-2015 10:45 PM

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

}


Don't want to miss updates? Please click the below button!

Follow MindStick