获得 JPanel 的焦点
我在 JFrame
内有一个 JPanel
。我已经注册了一个 KeyListener
,我想根据它更新 JPanel
。我遇到的问题是我无法将焦点放在 JPanel
上,因此我的 KeyListener
将无法工作。我已经知道 KeyListener
可以正常工作,因为我使用 JFrame
注册了它并且它工作得很好。我的代码现在是这样的:
myFrame.setFocusable(false);
myPanel.setFocusable(true);
myPanel.addKeyListener(myKL);
myFrame.add(myPanel);
以前有人遇到过这样的问题吗?我在这方面有什么遗漏吗?
PS:我的 JPanel 内没有任何组件,我只是在背景上绘制一个图像,因此我需要将焦点放在 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
尽管您指示面板可以聚焦,但面板并不要求聚焦。尝试使用 myPanel.requestFocus();。
Although you're indicating that the panel can be focusable, the panel isn't asking for focus. Try using
myPanel.requestFocus();
.使用
setFocusable(true)
,然后使用requestFocusInWindow()
。但后者必须在包含面板的窗口可见之后完成,为此您可能需要注册一个窗口侦听器并执行 requestFocusInWindow() 在窗口中激活处理程序代码。注意:特别是在窗口可见之后,而不是在调用
setVisible(true)
之后。Use
setFocusable(true)
and thenrequestFocusInWindow()
. 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 therequestFocusInWindow()
in the window activated handler code.Note: Specifically after the window is visible, not just after calling
setVisible(true)
.我有时会遇到类似的问题。我注意到,在某些情况下,最好将焦点放在框架内的面板内的特定控件上(例如,您想要键盘输入的输入框),而不是请求焦点集中在框架内的面板上。窗格本身。
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.
尝试
Try
尝试这样的事情:
Try something like this: