views:

148

answers:

4

Hello,

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.

+2  A: 

Although you're indicating that the panel can be focusable, the panel isn't asking for focus. Try using myPanel.requestFocus();.

David
Thanks for your answer. Tried both requestFocus() and requestFocusInWindow(), neither of them make the Panel get focus. Do you have any other suggestions?
Vlad T.
It may depend on when you call it. Don't call it in the JPanel's constructor, for example, since that gets called before the panel is displayed.
David
Thank you David, this answer worked for me, I had no idea that I couldn't make the call from the constructor. As soon as I moved the requestFocus() to a method that was getting called after the display on the screen it worked perfectly.
Vlad T.
A: 

I sometimes face a similar problem. I've noticed that in some cases it is better to make or request focus on a specific control within the panel that is within the frame (e.g., the input box to which you want keyboard input to go), rather than request focus for the pane itself.

Uri
A: 

Try

panel.setFocusable(true);
panel.setRequestFocusEnabled(true);

// some code here

panel.grabFocus();
John Doe
+2  A: 

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).

Software Monkey