Reputation: 68
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?
Upvotes: 0
Views: 791
Reputation: 205875
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.
Upvotes: 3