如何创建一个带有图像的复选框组?

我用:

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);
    }


但是ImageIcon和JCheckBox之间有很多空间。

最佳答案

不了解布局管理器,很难做到100%,但是如果我这样做,我可能会使用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++;
}


您可能还希望通读以下内容:


Retrieving Resources
Location-Independent Access to Resources
Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?
Reading/Loading an Image
Laying Out Components Within a Container
How to Use GridBagLayout

10-08 00:36