Java external Keylistener not responding

150 views Asked by At

I want to listen to keyboard inputs but i get no KeyCode, but the KeyListener have to be in an external class

Main.java:

public class Main {

    public static void main(String args[]){

        new Spielfeld("Spielfeld");
        new KeyEventListener();
    }

}

KeyEventListener.java

public class KeyEventListener implements KeyListener{

public KeyEventListener(){

}

@Override
public void keyPressed(KeyEvent e) {

    System.out.println(e.getKeyCode());

}

@Override
public void keyReleased(KeyEvent arg0) {}

@Override
public void keyTyped(KeyEvent arg0){}

}

Sorry, I'm new at Java and don't know how to fix this...

1

There are 1 answers

0
Neeraj Jain On BEST ANSWER

You need to add keyListener to any component such as JTextField ,

Here is a nice example :

public class KeyEventDemo ...  implements KeyListener ... {
    ...//where initialization occurs:
        typingArea = new JTextField(20);
        typingArea.addKeyListener(this);


    ...
    /** Handle the key typed event from the text field. */
    public void keyTyped(KeyEvent e) {
        displayInfo(e, "KEY TYPED: ");
    }

    /** Handle the key-pressed event from the text field. */
    public void keyPressed(KeyEvent e) {
        displayInfo(e, "KEY PRESSED: ");
    }

    /** Handle the key-released event from the text field. */
    public void keyReleased(KeyEvent e) {
        displayInfo(e, "KEY RELEASED: ");
    }

More on listeners : Here