How To Go To Item In ComboBox On Keypress In Java FX 2

This was annoying to begin with. In Swing, you do not have to worry about this because this feature is already part of it. In Java FX 2 however, it is not and I had to create a key listener to have the ComboBox select the first item that it comes across with that starts with the key character pressed.

And there is also another problem. If the ComboBox has so many items and the setVisibleRowCount() value is less than the number of the list size, it will not scroll down if the item selected is beyond the maximum visible row value.

It also took me some time to figure out how to get hold of the ListView reference from the ComboBox since this control is a combination of multiple controls: ListView, TextField and Button to name a few. You can only get hold of the ListView object from ComboBox if the popup is shown. Otherwise, you will get a NullPointerException.

So here is the key listener code.

How this works goes like this. When you type a character, it will go to the first item that matches that character, regardless of case sensitivity. If you transfer to another control, its cached characters will be removed so that when you go back to the ComboBox again, the cached string that you used to type will be reset.

You may notice that I also added an event filter for the ComboBox. This is because the ESC key does not get detected unless it is filtered. I really do not understand the inner workings but the ESC key gets detected only if it is captured in the event filter. When this happens, the keys will reset and any key you type will be considered as the first character.

I also added a mouse listener on the ComboBox so that when it is clicked and the popup list will appear, I will be able to get hold of the reference object to ListView and be able to call its scrollTo() method.

That’s it! To use this class, just call it like this:

Related Posts Plugin for WordPress, Blogger...

Leave a Reply

Your email address will not be published. Required fields are marked *