views:

175

answers:

2

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 cuz im 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 transfered to that panel somehow, but not sure at all.

Does and body know this and can help me out?

Thanks very much

+1  A: 

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:

http://stackoverflow.com/questions/2702203/keyboard-input-for-a-game-in-java/2702391#2702391

or this tutorial:

Swing: Understanding Input/Action Maps

aioobe
A: 

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

camickr