Swing offers nice possibilities to use a JComboBox with some sort of pre-selecting or type ahead features. One of the major drawbacks is, it does not remove items who don-not match at all (when typing).
In one of my projects it was required to filter out possibilities from the JComboBox when the user starts typing, so the list gets smaller when the user starts typing (large lists!). Of course the list grows back again when backspace is pressed(*).
I’ve found several solutions around, but non of them are completely satisfactory for me, mostly because they are to specific or to complex (maybe my solution isn’t the best either).
Some features and some drawbacks are known for the version presented in this issue:
- because of using backspace and rebuilding the JComboBox, all items must be present when an instance is created (* as shown earlier)
- because the user can enter text, the first item should be an empty one to hold the search term
- when no match occurs, getSelectedItem(0) is there to get the users query
For me it was important to use the getSelectedItem() method instead of the getSelectedIndex() method on an ActionEvent, since the user might have typed some text which was not present yet. The text from getSelectedItem() then is added to the database (in my application). Because of the filtering, double occurrences are minimized this way.
Link: FilteredTypeAheadComboBox.java
Link: FilteredTypeAheadDemo.java
Javawebstart: FilteredTypeAheadDemo.jnlp
.