本文介绍了重点关注一个JPanel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 JFrame
中有一个 JPanel
。我已经注册了一个 KeyListener
,我想更新 JPanel
。我遇到的问题是我不能把重点放在 JPanel
上,因此我的 KeyListener
不起作用。我已经知道 KeyListener
是功能性的,因为我使用 JFrame
注册它,并且它工作正常。我的代码现在是这样的:
myFrame.setFocusable(false);
myPanel.setFocusable(true);
myPanel.addKeyListener(myKL);
myFrame.add(myPanel);
有没有人遇到过这样的问题?有没有什么我缺少这方面的?
PS:我没有任何组件在 JPanel
我只是在背景上绘制一个图像,所以我需要把焦点放在JPanel本身上,而不是放在JPanel里面的东西上。 解决方案
p>虽然您表示该面板可以进行对焦,但面板并没有要求重点关注。尝试使用 myPanel.requestFocus();
。
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.
解决方案
Although you're indicating that the panel can be focusable, the panel isn't asking for focus. Try using myPanel.requestFocus();
.
这篇关于重点关注一个JPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!