Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...