KeyListener in JComboBox

You’ve seen those auto-complete combo boxes out there. SwingX has one, and it is a good one, but not exactly what I needed.  I didn’t want all of the highlighting and I didn’t want the options in the combo box to be static.  All my suggestions are coming from the database.

So what I discovered and what I want to share is how to listen for key events on an editable jComboBox.   If you did something like this:


jComboBox1.addKeyListener(new KeyListener() { ... }

You would not be notified of KeyEvents.  Why?  you ask.  When you type into an editable JComboBox the key events are not being fired on the JComboBox but rather on the editor of that JComboBox.


jComboBox1.getEditor().getEditorComponent().
addKeyListener(new KeyListener() { ... });

Simple as that!

About these ads

8 responses to “KeyListener in JComboBox

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 214 other followers

%d bloggers like this: