Search code examples
javaswingfocusjcomboboxkey-bindings

How to transfer focus a custom component when traversal keys are disabled?


I have created a custom JComboBox with a custom popup that implements the KeyListener. I wanted an item to be selected from the popup of the cmbBox on the press of either Tab or Enter hence I set the setFocusTraversalKeysEnabled(false) for both the combobox and the popup.

The problem with this approach is that now I have to add another KeyListener to the combobox when I use it in containers so as to shift the focus.

Can I fire a transfer focus event(hypothetically) or something like that within my custom JComponent which will transfer the focus in its parent component so that I dont have to add key listeners everywhere I use it. I have used transferFocus() but it is not transferring the focus.

I have not dirtied my hands on Key Bindings yet but is there a key binding to transfer the focus?

Thanks

I am trying to recreate a sscce but its proving difficult. Please bear.


Solution

  • Basic Listeners lifecycle is about to add required listener if is really needed, and remove Listener if is useless

    • I'd would be suggesting use KeyBindings, because this Listener is designated for Swing JComponents and sure you can (sure same as for KeyListener) add this listener to the concrete JComponent or its derivate(s)

    • you can add Listener to the derived popup on firePopupMenuWillBecomeVisible

    • you can add ItemListener to the derived JList

    • maybe not correct way but protect all defects implemented to the KeyListener, that only Focus owner can take events from keyboard, sure workaround for KeyBindings os more that settable and confortable

    notice please read this answer