2013-05-09 110 views
2

這是我在這裏的第一篇文章,以便提前道歉,如果這是可怕的......ListCellRenderer返回空指針

我試圖從自定義類的列表中添加項目到使用定製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的認識仍然有限,所以任何(簡單!)幫助都將不勝感激。

回答

2

你初始化的JLabel列數組:

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

但是你從來沒有填補這個數組的價值觀,所以他們會null當你想訪問它們。將每個元素設置爲new JLabel(),當你需要時,它們不會是null

+0

你真快。 +1 – 2013-05-09 21:03:15

+0

謝謝,這很快!空指針錯誤不再,但現在JList顯示爲空? – ms813 2013-05-09 21:10:58

+0

我已經回答了我自己的問題 - 我錯過了一個添加(標籤[i]);線。謝謝你的幫助! – ms813 2013-05-09 22:15:07

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

這是錯誤。您不要初始化數組中的任何標籤。