[英]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. 但是ImageIcon和JCheckBox之间有很多空间。
Without knowing the layout manager, it's difficult to be 100%, but if I was doing this, I might use a GridBagLayout
... 不了解布局管理器,很难做到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++;
}
You may also like to have a read through: 您可能还希望通读以下内容:
the space happens because you call .setPreferredSize(new Dimension(500, 50));
因为您调用.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. 在循环中创建的每个标签实例上,这会产生宽标签,因此将其删除,结果将很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.