如何使用带有图像的复选框组?
我用:
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之间还有很大的空间。
发布于 2015-01-12 23:32:19
在不知道布局管理器的情况下,很难做到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++;
}您还可以通过以下方式阅读:
发布于 2015-01-12 22:43:15
之所以会出现这种空间,是因为您在循环中创建的每个label实例上都调用了.setPreferredSize(new Dimension(500, 50));,这就产生了宽标签,所以删除它,结果就会很好。
https://stackoverflow.com/questions/27911289
复制相似问题