1 回答

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超8個(gè)贊
不要嘗試使用setMargin
方法來完成此操作,而是嘗試通過EmptyBorder
向渲染器添加 an 來完成此操作。new JCheckBox
另外,如果您在應(yīng)用程序中返回 aListCellRenderer
將使用大量內(nèi)存(它將不會(huì)返回到操作系統(tǒng)),因?yàn)槊看危◣缀酰┙M件被事件觸發(fā)/干擾時(shí),它都會(huì)被重新繪制,因此會(huì)產(chǎn)生新的 *cells JCheckBox 已創(chuàng)建。相反,創(chuàng)建一個(gè)新類extends JCheckBox
和implements ListCellRenderer
。另外,檢查setIconTextGap
方法。你可能想使用它:)
一個(gè)完整的例子:
public class CheckBoxInJList extends JFrame {
private static final long serialVersionUID = -1662279563193298340L;
public CheckBoxInJList() {
super("test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
DefaultListModel<String> model;
JList<String> list = new JList<>(model = new DefaultListModel<>());
for (int i = 0; i < 1000; i++) {
String s = "String: " + i + ".";
model.addElement(s);
}
list.setCellRenderer(new CheckBoxRenderer());
add(new JScrollPane(list), BorderLayout.CENTER);
setSize(500, 500);
setLocationRelativeTo(null);
}
private static class CheckBoxRenderer extends JCheckBox implements ListCellRenderer<String> {
public CheckBoxRenderer() {
super();
setBorder(BorderFactory.createEmptyBorder(0, 15, 0, 0));
}
@Override
public Component getListCellRendererComponent(JList<? extends String> list, String value, int index,
boolean isSelected, boolean cellHasFocus) {
setText(value);
setSelected(isSelected);
return this;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new CheckBoxInJList().setVisible(true);
});
}
}
預(yù)覽:
添加回答
舉報(bào)