[英]Margin to JCheckBox in a JList component
I have a JList component which has JCheckBox renderer as each item. 我有一个JList组件,每个项目都有JCheckBox渲染器。 I want to add margin to the checkBox so that it does not stick to the left side. 我想在checkBox中添加边距,使其不会粘在左侧。
I tried 我试过了
checkBox.setMargin(new Insets(0, 10, 0, 0)); //left side spacing
and also tried 并尝试过
checkBox.setAlignmentX(10.0F);
Rendering code 渲染代码
class ListRenderer() {
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
JCheckBox box = new JCheckBox("Married");
return box;
}
}
Both of them did not work. 他们俩都没用。
Instead of trying to do it with setMargin
method, try to do it by adding an EmptyBorder
to the renderer. 而不是尝试使用setMargin
方法,尝试通过向渲染器添加EmptyBorder
来实现。 Also, if you return a new JCheckBox
in your ListCellRenderer
your application will use a lot of memory (it will not be returned to OS) since every time (almost) the component fires/bothered by an event, it is being repainted and hence, new *cells JCheckBoxes are created.. Instead, create a new class that extends JCheckBox
and implements ListCellRenderer
. 此外,如果您在ListCellRenderer
返回一个new JCheckBox
,您的应用程序将使用大量内存(它将不会返回到操作系统),因为每次(几乎)组件被事件触发/打扰,它都被重新绘制,因此, new * cells创建JCheckBox ..相反,创建一个extends JCheckBox
并implements ListCellRenderer
的新类。 Also, check the setIconTextGap
method. 另外,检查setIconTextGap
方法。 You might want to use it :) 你可能想用它:)
A full example: 一个完整的例子:
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);
});
}
}
Preview: 预习:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.