Hi there 🙂 I am using Java 6, to start with.
Feature
When you are using a JComboBox, you can usually select an entry by typing characters. Which is nice.
Problem
Unfortunately, this does not work, if your entries are HTML strings, e.g. "<html><b>foo</b> <i>bar</i></html>". I am using HTML mainly for showing my entries in different colors, by the way.
Solution, bad
So, to solve this I implemented my own KeySelectionListener by altering JComboBox$DefaultKeySelectionManager, basically ignoring all tags, if an entry starts with "<html>".
That works. But: I was wrong thinking that the one used by default is JComboBox$DefaultKeySelectionManager. Why? Because it only handles the first character typed. For long lists with many entries starting with the same char, this isn’t convenient at all.
The good one, handling all characters typed into the box is BasicComboBoxUI$DefaultKeySelectionManager (which is the default). The problem is, that this one interacts with the nesting ComboBoxUI. It takes its JList and calls getNextMatch(prefix, …). Sadly JList.getNextMatch() does not care about HTML entries.
I can’t simply extend BasicComboBoxUI to have a different JList implementation, because the given LAF decides which UI is used.
Any ideas? Java 7 doesn’t solve this, I guess?
This is indeed a pita, and I’ve been confronted to the same problem. In the end, the combo box uses the toString() method of the objects contained in the model for its key selection. The easiest way is to wrap all your HTML strings into objects which have a toString() method returning the text used for selection, and use a cell renderer to render the HTML. For example:
And then fill your combo with these objects:
And set a renderer to the combo box which does