在JList中选择项时的java NullPointerException

时间:2013-10-23 05:01:18

标签: java swing nullpointerexception jlist defaultlistmodel

对于我的生活,我不能弄清楚我的JList有什么问题。我有一个DefaultListModel对象,其中包含从这些对象的HashMap填充的自定义数据类型。一切正常,直到组中有16个或更多对象。以下是发生的事情:

01 02 03 04 05

正如您所知,列表中突然出现空格,即使它填充的HashMap没有任何空对象。此外,这是用于填充JList的代码:

for(Entry<Integer, TV_Season_v2> e : rc.shows.get(index).seasons.entrySet()){
    seasonslistmodel.addElement(e.getValue());
}

,这是给出空指针异常的行:

int mapSeasonIndex = seasonsList.getSelectedValue().getSeasonNum();

发生了什么事?

3 个答案:

答案 0 :(得分:0)

如果您在上面给出的行中获得NPE,我确信seasonsList.getSelectedValue()null。来自JList.getSelectedValue()Javadoc:

  

如果没有选择,则返回{@code null}。

然后是空单元格...如果没有显示更多代码,我真的无法分辨,但对于某些条目,e.getValue()可能是null吗?

for(Entry<Integer, TV_Season_v2> e : rc.shows.get(index).seasons.entrySet()){
    seasonslistmodel.addElement(e.getValue());
}

答案 1 :(得分:0)

请确保 seasonsList 已正确初始化。

答案 2 :(得分:0)

对于任何绊倒我措辞严厉的问题的人来说,解决这个问题的方法是实现自己的循环来填充列表。

最初,我使用了java增强版for循环:

for(Entry<Integer, TV_Episode_v2> e : rc.shows.get(showIndex).seasons.get(mapSeasonIndex).episodes.entrySet()){
        episodeslistmodel.add(e.getKey()-1,e.getValue());
}

由于某些原因,如果episodes.size()大于15,此方法将遍历null结果,因此我实现了自己的迭代方法:

//Add elements to list model
int i = 0; //variable to show the index
int c = 0; //variable to count the number of episodes
while(c < rc.shows.get(showIndex).seasons.get(seasonIndex+1).episodes.size()){
    if(rc.shows.get(showIndex).seasons.get(seasonIndex+1).episodes.containsKey(i)){ //if the season contains the key i
        episodeslistmodel.add(i-1, rc.shows.get(showIndex).seasons.get(seasonIndex+1).episodes.get(i)); //add to the list
        c++; //increment up to count the number of objects found
    }
    i++;
}

这不会产生任何错误,并将所有项目放在JList中的适当位置。我希望这对阅读这篇文章的任何人都有帮助。