Well, since there is no built-in class that does this functionality, the only solution was to create my own. Here is my version of an auto-complete class that can be used for a TextField or editable ComboBox.

If you want to use this for a TextField node, just change parts of the code to cater to it. It should not be hard.

To use this class, just do

Easy, right?

This class also includes an added feature wherein after you type something in the editable ComboBox and when you press the ENTER key, an action will take place: say, you want to save it to the database or something.

Note: the focus listener is now added to the ComboBox’s TextField component because in the development environment, it works fine. However, when deployed as an Applet, it does not work. Only when I shifted the focus listener to the ComboBox’s editor did it work correctly.

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...