JPanel not listening to key event when there is a child component with JButton on it

我怕爱的太早我们不能终老 提交于 2019-11-28 14:23:46
aioobe

I suggest you use the InputMap and WHEN_ANCESTOR_OF_FOCUSED_COMPONENT or something similar. Excerpt from How to Use Key Bindings:

JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
The component contains (or is) the component that has the focus. This input map is commonly used for a composite component

That has worked very robustly for me. Have a look at my other post for more information and actual code examples:

Keyboard input for a game in Java

or this tutorial:

Swing: Understanding Input/Action Maps

camickr

You should NOT be using a KeyListener.

Swing was designed to use Key Bindings which is far more flexible. Check out my quick summary of Key Bindings which also includes a link to the Swing tutorial which conains far more detail.

(I can't post images here because I'm a new user)

An image doesn't help much anyway. If you need more help post your SSCCE which shows the problem (after trying the above suggestion).

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