Capturing keystrokes in a panel in java?

You need to add a new FocusListener and a new KeyListener to the panel. If you only want the keystrokes captured when the panel is in focus, get the FocusListener's action to add the KeyListener and remove it.

Don't forget to invoke setFocusable(true), as discussed in How to Write a Key Listener.

Depending on what you want to achieve, you could maybe also find help here: java.sun.com/products/jfc/tsc/special_re....

– fish May 13 '10 at 7:45 yeah I clicked the panel with my mouse and still nothing.. – rgksugan May 13 '10 at 7:47 Ok, removed that useless suggestion, but I'd suggest you take a look at the link and specifically ActionMap and InputMap there. Those might be what you are after. – fish May 13 '10 at 7:48.

Add KeyListener to your panel: JPanel panel = new JPanel(); panel. AddKeyListener(new KeyListener() { public void keyTyped(KeyEvent e) { … } public void keyReleased(KeyEvent e) { … } public void keyPressed(KeyEvent e) { … } }); Handle event with the corresponding method. As others precisely mentioned, you have to set panel.

SetFocusable(true); and, naturally, you ought to add this component to your frame (or other parent component).

I hav added the key listener..it doesn't work. – rgksugan May 13 '10 at 7:48.

Actually, what you want is a KeyboardManager to install a KeyEventPostProcessor, or even an alternate dispatch for various components. I had the same issues in a NB app as you did. Here's the article I used: (developer.Com) I did this to capture enter key events from any control in a panel (to initiate "OK" button behavior automatically): KeyboardFocusManager manager = KeyboardFocusManager.

GetCurrentKeyboardFocusManager(); manager. AddKeyEventPostProcessor(new EnterKeyListener()); And the listener: class EnterKeyListener implements KeyEventPostProcessor { @Override public boolean postProcessKeyEvent(KeyEvent e) { if (e.getKeyCode() == KeyEvent. VK_ENTER) { //Activate the refresh button: fireSearch(); return true; //halt further processing } return false; } }.

However you will still have problems because the default InputMap only receives the key events when it has focus and by default a JPanel is not focusable. The Key Bindings article attempts to simplify some of the key bindings concepts from the Swing tutortial.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions