JList display error with custom ListCellRenderer

I am having problems with one custom ListCellRenderer in a JList. When there is only 1 element in the list, the cell is displayed correctly, but when there is more than one element, each cell seam should be colored with the contents of all cells overlapping each other, for example:

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 installed 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 getSendungen() method returns ArrayList uiSendungsbutton .

How do I get JList to correctly display each element in a cell?

+4
source share
1 answer

The problem is that the same cell rendering is used for all cells, and for each new cell, components are added to this again. To fix this problem, remove all components from this each time using removeAll . Your code will look 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) { 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; } } 
-2
source

Source: https://habr.com/ru/post/1495454/