KeyListener problem
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.getHeigh开发者_如何学Pythont(), null);
}
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:
- Keyboard input for a game in Java
or this tutorial: Swing: Understanding Input/Action Maps
Related question:
- JPanel not listening to key event when there is a child component with JButton on it
精彩评论