This is indeed a tale of two mysteries. I was mystified upon seeing why my JComboBox ItemListener’s itemStateChanged() event method gets fired twice. There was only one way to solve it and that was to Google for it.

And the answer? Two events are fired whenever you select an item in the JComboBox: the deselect event and the select event.

If you insist in using an ItemListener for this, you would have to place an if statement within the itemStateChanged() method to handle only select or deselect events.

Frankly, I would suggest you use an ActionListener instead.

To sort items in a JComboBox object, check the code below. What the code does is compare the object to be added with the rest of the items that were already added. The compareToIgnoreCase() returns either a negative value if the first object less than the second one, 0 for equal and a positive value if it is greater than.

If the value returned is less than or equal to 0, the item will be inserted at the specified index of the item list else, add the item at the end of the item list.

There are ready-made classes of JComboBox that implement an autocomplete feature and I chose to use Orbital Computer because of its ease of use and simplicity of the code. I added an extra feature in this JComboBox wherein if you press the ESC key, it will automatically select and show the first item in the ComboBoxModel.

To use this class, simply call it like this.

That’s it! No need to actually create a variable for this class since you just pass the JComboBox object as the parameter and the class handles the rest adding the autocomplete feature. Pretty simple right? This is a handy class. Get the code below.

Related Posts Plugin for WordPress, Blogger...