简体   繁体   English

如何通过箭头键在Java Applet中使用Keylistener

[英]How to use a Keylistener in a Java Applet with the arrow keys

I am trying to create a simple game in a java applet, and I need to have my character move around (in four directions) using either the arrow keys or wasd (either should work). 我试图在Java小程序中创建一个简单的游戏,我需要使用箭头键或wasd(应该都可以)使我的角色在四个方向上移动。 I was unable to use arrows, so I tried this, which uses the capitol letters WASD instead: 我无法使用箭头,所以我尝试了此方法,该方法使用大写字母WASD代替:

public void keyPressed(KeyEvent e) {

    char c = e.getKeyChar();

    if ( (c == KeyEvent.VK_W) || (c == KeyEvent.VK_A) || (c == KeyEvent.VK_S) || (c == KeyEvent.VK_D) )
    {
        setboard();
    }
}

This works exactly how I want it to, but it is tedious to have to turn on caps lock every time I run the program. 这完全符合我的要求,但是每次我运行程序时都必须打开大写锁定很麻烦。

How can I change this program so that the KeyListener can sense lowercase letters and the arrow keys? 如何更改此程序,以便KeyListener可以感知小写字母和箭头键? VK_UP, VK_DOWN, VK_w, VK_a, etc. doesn't work. VK_UP,VK_DOWN,VK_w,VK_a等不起作用。

您可以在比较之前将char转换为大写,因此无论大写还是小写都没有关系:

 char c = Character.toUpperCase(e.getKeyChar());

To use the arrows, you're going to need to use getKeyCode() , which returns an int. 要使用箭头,您将需要使用getKeyCode() ,它返回一个int值。 Doing it this way solves your capital letters problem, too. 这样做也可以解决您的大写字母问题。 Like this: 像这样:

int code = e.getKeyCode();

if (code == KeyEvent.VK_W) {
    //do stuff
    //repeat with VK_A, VK_S, and VK_D
}

All the KeyEvent constants are ints underneath the hood anyway. 无论如何,所有KeyEvent常量都是引擎盖下的整数。

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

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