this is my first post here so apologies in advance if it is horrible...
I'm trying to add items from a list of custom classes into a JList using a custom ListCellRenderer. Each has a variety of things I would like to add to a row, with a new row being taken for each in the list:
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}
I sout the content of the list to make sure it is not null, but the line highlighted above returns a null pointer.
My knowledge of Java is still limited, so any (simple!) help would be much appreciated.
You initialize your array of JLabel
s:
private JLabel[] labels = new JLabel[3];
But you never fill this array with values, so they will be null
when you want to access them. Set each element with new JLabel()
and they won't be null
when you need them.