2

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.

Nitin Chhajer
  • 2,299
  • 1
  • 24
  • 35

1 Answers1

2

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

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • Thanks. Bullets 2 and 3 were part of my code and i am trying to shift to keybindings. What did the trick was in the combobox keylistener I had to replace `transferFocus()` with `((JComponent)e.getSource()).transferFocus()`. While debugging I found that source was **combobox editor and not the presumed combobox**. But I dont get why the focus was not shifting earlier. – Nitin Chhajer Apr 11 '12 at 21:41
  • Focus and FocusSubsystem is pretty asynchrounous, because came from Native OS, in most cases isn't possible (maybe your issue where more than one Listeners fired events to the EDT) manageing that wrapped into invokeLater(), nor to catch that as plain event – mKorbel Apr 11 '12 at 22:02