简体   繁体   中英

java NullPointerException when selecting items in a JList

I cannot, for the life of me, figure out what is wrong with my JList. I have a DefaultListModel object containing a custom data type which is populated from a HashMap of those objects. Everything works fine until there are 16 or more objects in the group. Here is what happens:

0102030405

As you can tell, there are suddenly empty spaces in the list, even though the HashMap it is populating from doesn't have any null objects. Also, here is the code used to populate the JList:

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

and here is the line which gives a null pointer exception:

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

What is going on?

If you get NPE in the line given above, I'm sure that seasonsList.getSelectedValue() is null . From the JList.getSelectedValue() Javadoc:

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

Then there's the empty cells... I really cannot tell without more code being shown, but could it be e.getValue() is null for some entries?

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

请确保seasonsList正确初始化。

The solution to this problem for anyone stumbling upon my badly-worded question is to implement ones own loop for populating the list.

Originally, I used a java enhanced for loop like so:

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

For some reason, this method iterates through null results if episodes.size() is greater than 15, so I implemented my own method of iteration:

//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++;
}

This produces no errors and puts all items in the proper place in the JList. I hope this is helpful to anyone reading this post.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM