简体   繁体   English

如何使用Keylistener / KeyAdapter

[英]How to use Keylistener/KeyAdapter

How would one, once they had set up a Keylistener or Keyadapter class and had overridden keyPressed and the other two, get the keyboard response in their program working? 一旦他们建立了Keylistener或Keyadapter类并覆盖了keyPressed和另外两个,如何在程序正常工作时获得键盘响应? For example, say I have my Keyadapter class all set up: 例如,假设我已经设置了我的Keyadapter类:

public class KeyInput extends Keyadapter {

public void keyPressed (KeyEvent e) {

    int key = e.getKeyCode();

    if (key == VK_W) {
        System.out.println("You pressed W");

    }

}

} }

How would I go from there, to make it so it would actually detect it and display the string whenever I would press W? 我将如何从那里去制作它以便它实际上可以检测到它并在每当我按W键时显示该字符串? There aren't any methods that I could call in the main method to make it start checking, are there? 我可以在main方法中调用任何方法以使其开始检查,是吗? If not how does the JVM know to start checking if there isn't a method in main to tell it to? 如果不是,那么JVM如何知道开始检查main中是否没有要告知的方法?

Thank you for your time. 感谢您的时间。

KeyAdapter is a java awt class. KeyAdapter是java awt类。 Your KeyInput (keylistener) has to be registered with another awt component to start listening to key events. 您的KeyInput(键侦听器)必须注册到另一个awt组件才能开始侦听键事件。

An example of what you are looking for can be found here 您正在寻找的示例可以在这里找到

JButton button = new JButton("Clear");
button.addActionListener(this);

typingArea = new JTextField(20);
typingArea.addKeyListener(new KeyInput());

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

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