JList显示自定义ListCellRenderer的错误

时间:2013-08-06 06:37:05

标签: java swing listcellrenderer

我在JList上遇到一个自定义ListCellRenderer时遇到问题。当列表中只有一个项目时,单元格显示正确,但当有多个项目时,每个单元格接缝将被绘制,所有单元格的内容相互重叠,如下所示:

enter image description here

我的CellRenderer看起来像这样:

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;
    }

}

并使用

设置
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());

方法getSendungen()返回uiSendungsbutton

的ArrayList

如何让JList正确显示自己单元格中的每个项目?

1 个答案:

答案 0 :(得分:-2)

问题是所有单元格都使用相同的单元格渲染器,并且对于每个新单元格,您再次将组件添加到this。要解决此问题,请每次使用thisremoveAll删除所有组件。修复后,您的代码将如下所示:

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;
    }
}