这是我在这里的第一篇帖子,如果太可怕,请提前道歉。。。
我正在尝试使用自定义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}
我搜索列表的内容以确保它不是null,但上面突出显示的行返回一个null指针。
我对Java的了解仍然有限,所以任何(简单的!(帮助都将不胜感激。
初始化JLabel
的数组:
private JLabel[] labels = new JLabel[3];
但是您永远不会用值填充这个数组,所以当您想要访问它们时,它们将是null
。用new JLabel()
设置每个元素,当您需要它们时,它们就不会是null
。
private JLabel[] labels = new JLabel[3];
这是错误。您不初始化数组中的任何标签。