gpt4 book ai didi

java - ListCellRenderer 返回空指针

转载 作者:行者123 更新时间:2023-12-04 04:58:19 25 4
gpt4 key购买 nike

这是我在这里的第一篇文章,如果它太可怕了,请提前道歉......

我正在尝试使用自定义 ListCellRenderer 将自定义类列表中的项目添加到 JList 中。每个都有各种我想添加到一行的东西,列表中的每个都有一个新行:

    public class MatchRecord {
private String player;
private Integer kills;
private Integer deaths;
private Integer assists;//getters + setters etc etc below}
private class GameStatistics{//this is the main class of the program

listModel = new DefaultListModel();
jList.setModel(listModel);
listModel.clear(); //get rid of any junk in the list before loading
recordJList.setLayoutOrientation(JList.VERTICAL);

//add the records to the JList
recordJList.setCellRenderer(new RecordListRenderer());

List<MatchRecord> list = new ArrayList();
list.addAll(recordSet); //recordSet is a Set<MatchRecord> which has been previously loaded from file

for(int i = 0; i < list.size(); i++){
System.out.println(list.get(i).getPlayer()); //this is NOT NULL!
listModel.addElement(list.get(i));
}
}
    public class RecordListRenderer extends JPanel implements ListCellRenderer {

private JLabel[] labels = new JLabel[3];

public RecordListRenderer(){
setOpaque(true);
setLayout(new GridLayout(1, 4));

//set font size + colour here
}

public Component getListCellRendererComponent(JList list,
Object r,
int index,
boolean isSelected,
boolean hasFocus){

MatchRecord record = (MatchRecord) r;

labels[0].setText(record.getPlayer()); //This line returns a null pointer
labels[1].setText(record.getKills());
labels[2].setText(record.getDeaths());
labels[3].setText(record.getAssists());
return this}

我列出了列表的内容以确保它不为空,但上面突出显示的行返回一个空指针。

我对 Java 的了解仍然有限,因此非常感谢任何(简单!)帮助。

最佳答案

你初始化你的数组 JLabel s:

private JLabel[] labels = new JLabel[3];

但是你永远不会用值填充这个数组,所以它们将是 null当您想访问它们时。用 new JLabel() 设置每个元素他们不会是 null当你需要它们时。

关于java - ListCellRenderer 返回空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16470967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com