Vlad T.
Vlad T.

Reputation: 265

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.

Upvotes: 23

Views: 43486

Answers (5)

Bram Janssens
Bram Janssens

Reputation: 155

Try something like this:

    myFrame.addFocusListener(new FocusAdapter() {

        /**
         * {@inheritDoc}
         */
        @Override
        public void focusGained(FocusEvent aE) {
            myPanel.requestFocusInWindow();
        }
    });

Upvotes: 2

L. Cornelius Dol
L. Cornelius Dol

Reputation: 64065

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

Upvotes: 7

John Doe
John Doe

Reputation: 867

Try

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

// some code here

panel.grabFocus();

Upvotes: 2

Uri
Uri

Reputation: 89859

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.

Upvotes: 2

David Koelle
David Koelle

Reputation: 20834

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

Upvotes: 25

Related Questions