2

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.

Nash
  • 452
  • 1
  • 4
  • 16
Razzo
  • 47
  • 1
  • 6

2 Answers2

1

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:

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

the space happens because you call .setPreferredSize(new Dimension(500, 50)); on each label instance created on your loop,which resulting wide label, so remove it and the result will just fine.

Fevly Pallar
  • 3,059
  • 2
  • 15
  • 19
  • oh ya and calling .getClass().getResource() is preferred , just like @MadProgrammer said it to you. – Fevly Pallar Jan 12 '15 at 22:45
  • without label.setPreferredSize(new Dimension(500, 50)); I have the same problem. :( – Razzo Jan 12 '15 at 23:26
  • [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/questions/7229226/should-i-avoid-the-use-of-setpreferredmaximumminimumsize-methods-in-java-swi) – MadProgrammer Jan 12 '15 at 23:32
  • @Razzo, it must be it, because I tested your code also. When remove it the space between checkbox & icon is dissappeared, or perhaps you use some layouts to manages the space like GridLayout maybe.. – Fevly Pallar Jan 13 '15 at 00:10