简体   繁体   English

Java AWT KeyListener不起作用

[英]Java AWT KeyListener not working

I have been playing around with Java and I added a KeyListener. 我一直在玩Java,并添加了KeyListener。 When I type a key it prints "0" and I would like it to print the key code. 当我键入一个键时,它会显示“ 0”,并且我希望它显示键代码。

Key.java 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 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. 有关键类型事件的定义,请参见KeyEvent的类描述。

So go through the description : 因此,通过描述:

public int getKeyCode()

Returns the integer keyCode associated with the key in this event. 返回与此事件中的键关联的整数keyCode。 Returns: the integer code for an actual key on the keyboard. 返回:键盘上实际键的整数代码。 ( For KEY_TYPED events, the keyCode is VK_UNDEFINED .) 对于KEY_TYPED事件,keyCode为VK_UNDEFINED 。)

And the constant VK_UNDEFINED is : 常量VK_UNDEFINED为:

public static final int VK_UNDEFINED = 0;

So that's totally normal you only get 0. 所以这完全正常,您只会得到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. 对于KEY_TYPED事件,键码未定义。 Check the java docs: http://docs.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html#getKeyCode() 检查Java文档: http://docs.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html#getKeyCode() : http://docs.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html#getKeyCode()

Use getKeyChar() instead. 使用getKeyChar()代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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