0
    listItemsCombo.getEditor().getEditorComponent().addKeyListener(new keyPressListener()); //Works correct

This works fine. But , On adding keyListener to the jcomboBox , keyPress is not getting recoganized while pressing "Enter". What is the exact difference between adding a keyListener to the jComboxBox and adding a listener to its editor?When to add Listeners to editor?

   listItemsCombo.addKeyListener(new KeyPressListener())//When should we use this?
divya
  • 11
  • 6
  • possible duplicate of [Java Editable JCombobox Keylistener event for Enter key](http://stackoverflow.com/questions/14056301/java-editable-jcombobox-keylistener-event-for-enter-key) – Paco Abato Mar 02 '15 at 11:49
  • It works well when I use editor's listener.But my question is when to use it?Y we use it? – divya Mar 02 '15 at 11:55

1 Answers1

0

What is the exact difference between adding a keyListener to the jComboxBox and adding a listener to its editor?

KeyEvents are only dispatched to the component that has focus.

When to add Listeners to editor?

You should not use a KeyListener on the combo box or the editor. Swing was designed to be used with Key Bindings. With Key Bindings you can handle a KeyStroke even if the components doesn't have focus (if you wish). Read the section from the Swing tutorial on How to Use Key Bindings for more information.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • KeyBindings can be used. I need to Listen to the KeyTyped too. KeyBindings can be used for KeyPress. But for getting userInput from the keyBoard (keys like abc ..), I need to add a keyListener right?Or it can be performed with keyBindings? – divya Mar 03 '15 at 05:40
  • @divya, Key Bindings is used when you want to invoke an Action when a specific key is pressed. If you just want to know when text is added to the text field then you should use a `DocumentListener`. The tutorial also has a section on "How to Write a DocumentListener". – camickr Mar 03 '15 at 07:01