1

I have a JComboBox with an key listener.

When I hit <enter>, I fire off some action, and then I need to to lose focus on the JComboBox!

To focus on it, I can do JComboBoxObject.grabFocus();

But doing transferFocus() to get the focus to a next element (I don't care WHERE the focus goes, just away from combo box) does NOT work.

Doing grabFocus() from another combo box works, but seems like a pretty annoying hack to me. Is there a better solution?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
DVK
  • 126,886
  • 32
  • 213
  • 327
  • 1
    unrelated: sigh ... don't use keylisteners .. related: transferFocus (used on the currently focused compoent) should work, if it doesn't better show a SSCCE demonstrating what _exactly_ you are doing/trying to achieve. BTW, you did read the tutorial on how to use JComboBox, didn't you? It has something to say on low-level listeners and (potentially - you can't really know) compound components :-) – kleopatra Aug 07 '13 at 19:20

2 Answers2

3

Updated: Starting from this two-combo example, adding either of these lines to the actionPerformed() implementation seems to do what you want.

combo1.transferFocus();
combo2.requestFocusInWindow();
Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • you don't really recommend hard-coding the other component, do you :-) – kleopatra Aug 07 '13 at 19:23
  • @kleopatra is right: I took "don't care" a bit too literally; you should ask the `FocusTraversalPolicy` of the enclosing `Container`, as the deprecated `getNextFocusableComponent()` API suggests. – trashgod Aug 07 '13 at 19:32
  • 2
    actually, asking the traversalPolicy is too low-level (you would have to walk up until you find the one that's applicable, also checking the isTraversalPolicyProvider properties and other thingies that I don't remember) - component.transferFocus should just work fine. – kleopatra Aug 07 '13 at 19:40
3

I can suggest you to first use the

.getNextFocusableComponent()

and then use the

.requestFocusInWindow()

that means Implementing it like this,

JComboBox.getNextFocusableComponent().requestFocusInWindow();

One important note is that .getNextFocusableComponent() has become obsolete but it can work really better, you can use it but If you have any other solution, I would prefer not using this.

MMujtabaRoohani
  • 483
  • 4
  • 19