I have a JPanel
inside a JFrame
. I have registered a KeyListener
, based on which I want to update the JPanel
. The problem I am having is that I cannot get the focus on the JPanel
and therefore my KeyListener
won't work. I already know that the KeyListener
is functional because I registered it with the JFrame
and it worked fine. My code goes something like this at the moment:
myFrame.setFocusable(false);
myPanel.setFocusable(true);
myPanel.addKeyListener(myKL);
myFrame.add(myPanel);
Has anyone encountered a problem like this before? Is there something I am missing in regards to this?
P.S.: I do not have any components inside the JPanel
I just draw an Image on the background, so I need the focus to be on the JPanel itself and not on something inside it.
The component must always be either a Frame or a Dialog . The active window is either the focused window, or the first frame or dialog-box that is an owner of the focused window. The default focus traversal policy, which can be set by the setFocusTraversalPolicy method of the Container class.
setFocusable() is actually a method from the Component class in Swing. It lets the component (in your case, JPanel which extends Component ) have the power of getting focused.
requestFocus() makes a request that the given Component gets set to a focused state. This method requires that the component is displayable, focusable, visible and have all it's ancestors be visible too.
Although you're indicating that the panel can be focusable, the panel isn't asking for focus. Try using myPanel.requestFocus();
.
Use setFocusable(true)
and then requestFocusInWindow()
. But the latter must be done after the window containing the panel is made visible, for which you will likely need to register a window listener and do the requestFocusInWindow()
in the window activated handler code.
Note: Specifically after the window is visible, not just after calling setVisible(true)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With