# Add Keyboard listener to a java code



## abhinav_bipnesh (Sep 23, 2008)

Hi,

I am trying to add key board listener to my Swing code but enable to do so as i am able to use mouse click event for button press. Now I want to add a key listener to my code so that even when a numeric key is pressed then the text field has the input.
The code is given below.


> import java.awt.Image;
> import java.awt.Toolkit;
> 
> /*
> ...



Some code is auto generated using NetBean IDE so may be you have to tell how to add the code in the IDE as i am using the same ide to write the code.

Thanks in advance.


----------



## chandru.in (Sep 24, 2008)

Do not post such long code as it is very cumbersome to read and understand.  *See this page about SSCCE*.

Your requirement can be achieved by adding an individual key listener to every component in the Frame.  But it is a very poor way of doing it as it makes your code more VB like and leads to too much of unnecessary code.  Here is one way of achieving what you want without such unnecessary code mess.  This code just adds whatever character is typed.  You may want to filter out characters in your listener code.


```
KeyListener listener = new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                char ch = e.getKeyChar();
                textField.setText(textField.getText() + ch);
            }
        };

        Component[] components = getContentPane().getComponents();
        for (Component comp : components)
            comp.addKeyListener(listener);
```
Adding this code fragment in your construtor after the statement invoking initializeComponents(), should do the trick for you.


----------

