0

like the title says. I'm trying to figure out how to keep the focus on the JFrame or perhaps the window. So that when I press F1 on the keyboard, it activates a method. And it should also do it when I'm typing in a textfield.

I have read through the "How to Use the Focus Subsystem" but can't find what I'm looking for. Or maybe I just don't know where to look.

I tried using contentPane.setFocusable(true); but it looses focus when I activate another component. So how do I get it to keep focus?

blackpanther
  • 10,998
  • 11
  • 48
  • 78
  • Don't use a key listener for this; use key bindings or `frame.getRootPane().setDefaultButton()` – trashgod Jan 15 '14 at 11:38
  • a KeyListener is more flexible and you can map more responses than with setDefaultButton – Typo Jan 15 '14 at 11:39

1 Answers1

3

You may be trying to solve the wrong problem caused by using a KeyListener, which requires focus. Instead, use key bindings or setDefaultButton(), found in the frame's root pane.

Addendum: I tried key bindings, and solved it almost. It still does not work when a JTextField is selected. Do you maybe have a solution for that?

Depending on your needs, consider a DocumentListener or DocumentFilter. See this Q&A for more on the two.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • A KeyListener does not bring troubles...and can be used by more than one component – Typo Jan 15 '14 at 11:49
  • @alex2410 Again...a KeyListener does not bring troubles, key binding is a suitable solution, but not the only one. – Typo Jan 15 '14 at 11:57
  • thanks for the respons. I agree with you that keylistener is not the way to go. I tried setDefaultButton. But that seemed to work for only one key(I should have mentioned that i also want F2, F3 etc. to work). So I tried keyBindings, and solved it almost. It still does not work when a JtexField is selected. Do you maybe have a solution for that? – Slang2856223 Jan 15 '14 at 12:49
  • @Slang2856223 whats the word?? let me hear it!!! k k k k ...keeeeeyliiiisteneeersss – Typo Jan 15 '14 at 16:04
  • @Slang2856223: key bindings are the more flexible approach; more above for `JTextComponent` subclasses. – trashgod Jan 15 '14 at 16:22
  • @trashgod no they're not – Typo Jan 15 '14 at 17:59