views:

63

answers:

1

In my apllication i am using a jpanel in which i want to add a key listener. I did it. But it doesnot work.

Is it because i am using a swingworker to update the contents of the panel every second.

Here is my code to update the panel

RenderedImage image = ImageIO.read(new ByteArrayInputStream((byte[]) get()));
        Graphics graphics = remote.rdpanel.getGraphics();
        if (graphics != null) {
            Image readyImage = new ImageIcon(UtilityFunctions.convertRenderedImage(image)).getImage();
            graphics.drawImage(readyImage, 0, 0, remote.rdpanel.getWidth(), remote.rdpanel.getHeight(), null);
        }
+1  A: 

Does the JPanel have keyboard focus?

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

The WHEN_IN_FOCUSED_WINDOW input maps of all the enabled components in the focused window are searched. Because the order of searching the components is unpredictable

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

Related question: http://stackoverflow.com/questions/2793002/jpanel-not-listening-to-key-event-when-there-is-a-child-component-with-jbutton-on

aioobe