Margin to JCheckBox in a JList component

user1184100 :

I have a JList component which has JCheckBox renderer as each item. I want to add margin to the checkBox so that it does not stick to the left side.

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.

enter image description here

George Z. :

Instead of trying to do it with setMargin method, try to do it by adding an EmptyBorder to the renderer. 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. Also, check the setIconTextGap method. 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:

enter image description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=140612&siteId=1