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

六眼飞鱼酱① 提交于 2019-11-27 08:28:41

问题


I'm working on a map editor for my college project. And I had a problem that the map panel is not listening key event while it should. This happens when I add a ToolBarPane (which extends JPanel) with JComponent such as JButton, JComboBox that implements ActionListener on it AND the map panel (which extends the JPanel) together on to the Frame (I used BorderLayout). I have System.out.println statement to test if the key press is received, and it's not printing, if I remove the ToolBar, the key listener works again, so is the mouseListenner is disabled just like the keyListener, which means I can't handle press events etc, but the mouseListener works fine and I can still handle mouse move event.

Here is a screen shot how it works without the ToolBarPane

http://img684.imageshack.us/img684/3232/sampleku.png

note that you can use the mouse to put images on the map, you can also select images using the mouse just like a laser tool, and by pressing number key you can switch between different images, this works fine until I add the ToolBarPane which shows like this:

img291.imageshack.us/img291/8020/failve.png (please add http before that, I can only post one hyperlink)

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

With the ToolBarPane on I was no longer able to handle the key event.

I guess it might by that the focus as been transferred to that panel somehow, but not sure at all.

Does and body know this and can help me out?

Thanks very much


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/2793002/jpanel-not-listening-to-key-event-when-there-is-a-child-component-with-jbutton-o

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