Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining focus on a JPanel

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.

like image 429
Vlad T. Avatar asked Jan 25 '10 20:01

Vlad T.


People also ask

What frame receives focus by default?

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.

What does setFocusable do in Java?

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.

What is requestFocus in Java?

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.


2 Answers

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

like image 117
David Koelle Avatar answered Sep 30 '22 18:09

David Koelle


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

like image 36
Lawrence Dol Avatar answered Sep 30 '22 18:09

Lawrence Dol