Obtaining focus on a JPanel

爷,独闯天下 提交于 2019-11-26 21:10:25

问题


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.


回答1:


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




回答2:


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




回答3:


Try

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

// some code here

panel.grabFocus();



回答4:


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.




回答5:


Try something like this:

    myFrame.addFocusListener(new FocusAdapter() {

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


来源:https://stackoverflow.com/questions/2135223/obtaining-focus-on-a-jpanel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!