有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在JList中选择项目时swing java NullPointerException

就我个人而言,我无法找出我的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) 个答案

  1. # 1 楼答案

    请确保季节列表已正确初始化

  2. # 2 楼答案

    对于任何遇到我这个措辞糟糕的问题的人来说,解决这个问题的方法就是实现自己的循环来填充列表

    最初,我使用了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());
    }
    

    出于某种原因,如果出现错误,该方法将遍历空结果。size()大于15,所以我实现了自己的迭代方法:

    //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中的正确位置。我希望这对阅读本文的人有所帮助

  3. # 3 楼答案

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

    Returns {@code null} if there is no selection.

    然后是空的牢房。。。如果没有更多的代码显示,我真的说不出来,但是对于一些条目,它可能是e.getValue()null

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