如何检测Java中是否按下了某个键? [英] How to detect if a key was pressed in Java?

查看:527
本文介绍了如何检测Java中是否按下了某个键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的初学者,我一直在研究如何检测用户是否按下了某个键(例如箭头键)。显然有很多方法可以做这样的事情,我发现这个方法对我有用:

I am a beginner in Java an I have been looking on how to detect if the user pressed a key (such a the arrow keys). Apparently there are a lot of ways to do such a thing, and I found that this method should work for me:

public void keyPressed(KeyEvent e) {
    int keyCode = e.getKeyCode();
    switch( keyCode ) { 
        case KeyEvent.VK_UP:
            // handle up 
            break;
        case KeyEvent.VK_DOWN:
            // handle down 
            break;
        case KeyEvent.VK_LEFT:
            // handle left
            break;
        case KeyEvent.VK_RIGHT :
            // handle right
            break;
     }
}

问题是我不知道KeyEvent是什么是。$
当我打电话给方法并告诉我一个例子时,有人能告诉我括号中的内容吗?

The problem is that I have no idea what a KeyEvent is.
Can anyone tell me what to put in the parentheses when I call the method and show me an example please?

PS:don'把我送到另一个网站,我可能已经看过了,他们只是让我更加困惑......

PS: don't send me to an other site, I probably have already looked at it and they just confuse me more...

推荐答案

public class KeyEvent
extends InputEvent

表示的事件在组件中发生击键。

An event which indicates that a keystroke occurred in a component.

当键为

按下,释放或输入。该事件被传递给每个KeyListener或KeyAdapter对象

pressed, released, or typed. The event is passed to every KeyListener or KeyAdapter object

,它们使用组件的addKeyListener方法注册接收此类事件。

which registered to receive such events using the component's addKeyListener method.

(KeyAdapter对象实现KeyListener接口。)每个这样的侦听器对象在事件发生时获取此KeyEvent。

(KeyAdapter objects implement the KeyListener interface.) Each such listener object gets this KeyEvent when the event occurs.

并使用该事件对象,您可以使用 e.getKeyCode()等更多方法获取事件详细信息,例如按下了哪个键。

and using that event object, you can get the event details like what key has been pressed using e.getKeyCode() some more methods like that.

这篇关于如何检测Java中是否按下了某个键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆