Question

I am having trouble with one a custom ListCellRenderer on a JList. When there is only 1 item in the List the cell is displayed correctly, but when there is more than 1 item, each cell seams to be painted with the content of all cells overlapping each other, like this:

enter image description here

My CellRenderer looks like this:

public class SendungsCellRenderer extends JPanel implements ListCellRenderer {

private EmptyBorder eb = new EmptyBorder(5, 2, 5, 2);
private LineBorder lb = new LineBorder(new Color(255,255,255), 5);

@Override
public Component getListCellRendererComponent(JList list, Object value,
        int index, boolean isSelected, boolean cellHasFocus) {

    uiSendungsbutton p = (uiSendungsbutton) value;
    if(isSelected){
        this.setBackground(new Color(200,200,250));
        this.setBorder(new CompoundBorder(lb, new StrokeBorder(new BasicStroke())));
    }else{
        this.setBackground(new Color(252,252,252));
        this.setBorder(lb);
    }
    this.setLayout(p.getLayout());
    this.add(p.getNamePnl(),BorderLayout.NORTH);
    this.add(p.getKdnrPnl(), BorderLayout.CENTER);
    return this;
    }

}

and it is set using

list_Sendung = new JList(getSendungen().toArray());
list_Sendung.setVisibleRowCount(1);
list_Sendung.setValueIsAdjusting(true);
list_Sendung.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list_Sendung.setCellRenderer(new SendungsCellRenderer());

The method getSendungen() returns an ArrayList of uiSendungsbutton.

How do I get the JList to display each item in a cell of its own correctly?

Was it helpful?

Solution

The problem is that the same cell renderer is being used for all cells, and for each new cell, you add the components to this again. To fix this problem, remove all components from this each time, using removeAll. Your code would look like this after it was fixed:

public class SendungsCellRenderer extends JPanel implements ListCellRenderer {

    private EmptyBorder eb = new EmptyBorder(5, 2, 5, 2);
    private LineBorder lb = new LineBorder(new Color(255,255,255), 5);

    @Override
    public Component getListCellRendererComponent(JList list, Object value,
            int index, boolean isSelected, boolean cellHasFocus) {
        this.removeAll();
        uiSendungsbutton p = (uiSendungsbutton) value;
        if(isSelected){
            this.setBackground(new Color(200,200,250));
            this.setBorder(new CompoundBorder(lb, new StrokeBorder(new BasicStroke())));
        }else{
            this.setBackground(new Color(252,252,252));
            this.setBorder(lb);
        }
        this.setLayout(p.getLayout());
        this.add(p.getNamePnl(),BorderLayout.NORTH);
        this.add(p.getKdnrPnl(), BorderLayout.CENTER);
        return this;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top