Handling selections when filtering a JList

I wrote code to provide iTunes-like filtering of a JList. The only interesting part (ignoring the UI, which I've mentioned already in A Cocoa-like search field for Java) was notifying listeners.

The premature optimizer might think they can get away with fireContentsChanged, but JList interprets that as meaning that the structure of the list hasn't changed. It accepts that it needs to redraw, but it won't realize that its selection model has been invalidated.

To fix this, I invoke fireIntervalRemoved for the interval [0, original model size) and then fireIntervalAdded for the interval [0, filtered model size). Which is okay, because you don't now have the wrong items selected, but it's not right, because you don't have any items selected.

iTunes does the right thing, so an item that was selected before filtering remains selected if it survives filtering. What I dislike about this is that you lose the ability to make the round trip: if you cancel the filter, you don't get the old selection back. You still just have the selected items that survived the filtering.

So while I wonder about what the right behavior is, and even wonder if there is a "right" behavior, I'm going to do nothing and wait until the current behavior becomes a problem in one of the applications I use FilteredListModel in.

If you want iTunes-like search functionality on a JList in your Swing application, and can live with the GPL, you can download the code as part of the oddly-named "salma-hayek" library. It doesn't yet have a web page of its own, but it's linked to from the page for SCM, for example.

JTable "coming soon", and JTree when I work out how to do it.