简体   繁体   中英

Java AWT KeyListener not working

I have been playing around with Java and I added a KeyListener. When I type a key it prints "0" and I would like it to print the key code.

Key.java

import java.awt.event.*;

public class Key implements KeyListener {
public void keyPressed(KeyEvent e) {

}

public void keyReleased(KeyEvent e) {

}

public void keyTyped(KeyEvent e) {
    System.out.println("TYPED: " + Integer.toString(e.getKeyCode()));
}
}

Main.java

public void init() {
    addKeyListener(new Key());
    addMouseListener(new Mouse());

    this.setBackground(new Color(100, 100, 255));
    this.setSize(screen);
}

Thanks for all the help!

Just read the doc :

void keyTyped(KeyEvent e)

Invoked when a key has been typed. See the class description for KeyEvent for a definition of a key typed event.

So go through the description :

public int getKeyCode()

Returns the integer keyCode associated with the key in this event. Returns: the integer code for an actual key on the keyboard. ( For KEY_TYPED events, the keyCode is VK_UNDEFINED .)

And the constant VK_UNDEFINED is :

public static final int VK_UNDEFINED = 0;

So that's totally normal you only get 0.

You should use :

public void keyTyped(KeyEvent e) {
    System.out.println("TYPED: " + e.getKeyChar());
}

Here's an example using the three methods.

For KEY_TYPED event, the Key Code is undefined. Check the java docs: http://docs.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html#getKeyCode()

Use getKeyChar() instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM