I'm trying to add a key listener to a component that explicity doesn't listen, I mean, I'm using a JPanel as a drawing area, well as a matter of fact, I want to hear the key events, I have tried the following cases,
public class Pizarron extends JPanel { JPanel areaDib; Pizarron() { areaDib = new JPanel(); areaDib.addKeyListener(new MyKeyListener()); }
private class MyKeyListener extends KeyAdapter { public void keyPressed (KeyEvent e) { System.out.println(e.getKeyText (e.getKeyCode())); }
public void keyReleased (KeyEvent e) { System.out.println(e.getKeyText(e.getKeyCode())); }
public void keyTyped (KeyEvent e) { System.out.println(e.getKeyChar()); } }
}
I've been doing the same listeners inner classes with Mouse Listener, and it works!, really it works in a very easy way, but,
what happened with non-key listener components?, is there some other special stuff that I have to do?
Hi By default, JPanel cannot gain focus. You need to override isFocusTraversable() method for your JPanel and then return true from this method. Now your JPanel can gain focus and hence can also receive key strokes and your key events will work fine. In the following example, I have used your JPanel with little modification and then I have added your JPanel inside a frame . Now when you compile and run this code then your key strokes will be handled by the your key event handlers defined in your JPanel and you can see messages being printed out on console. However, if you add more controls (e.g. a JButton) to the frame then you will have to tab to JPanel so that it has focus and then you can handle key strokes in JPanel. Thanks Kishori