简体   繁体   English

如何处理Java中的同时按键?

[英]How do I handle simultaneous key presses in Java?

How do I handle simultaneous key presses in Java? 如何处理Java中的同时按键?

I'm trying to write a game and need to handle multiple keys presses at once. 我正在尝试编写游戏,并且需要一次处理多个按键。

When I'm holding a key (let's say to move forward) and then I hold another key (for example, to turn left), the new key is detected but the old pressed key isn't being detected anymore. 当我按住一个键(假设向前移动),然后按住另一个键(例如,向左转)时,将检测到新键,但不再检测到旧的键。

One way would be to keep track yourself of what keys are currently down. 一种方法是跟踪自己当前按下了哪些键。

When you get a keyPressed event, add the new key to the list; 当您收到keyPressed事件时,将新键添加到列表中;否则,将新键添加到列表中。 when you get a keyReleased event, remove the key from the list. 当您收到keyReleased事件时,请从列表中删除密钥。

Then in your game loop, you can do actions based on what's in the list of keys. 然后,在游戏循环中,您可以根据按键列表中的内容进行操作。

Here is a code sample illustrating how to perform an action when CTRL+Z is pressed: 这是一个代码示例,说明了按CTRL + Z时如何执行操作:

import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
class p4 extends Frame implements KeyListener
{
    int i=17;
    int j=90;
    boolean s1=false;
    boolean s2=false;

    public p4()
    {
        Frame f=new Frame("Pad");

        f.setSize(400,400);
        f.setLayout(null);
        Label l=new Label();
        l.setBounds(34,34,88,88);
        f.add(l);

        f.setVisible(true);
        f.addKeyListener(this);
    }

    public static void main(String arg[]){
        new p4();
    }

    public void keyReleased(KeyEvent e) {
        //System.out.println("re"+e.getKeyChar());

        if(i==e.getKeyCode())
        {
            s1=false;
        }

        if(j==e.getKeyCode())
        {
            s2=false;
        }
    }

    public void keyTyped(KeyEvent e) {
        //System.out.println("Ty");
    }

    /** Handle the key pressed event from the text field. */
    public void keyPressed(KeyEvent e) {
        System.out.println("pre"+e.getKeyCode());

        if(i==e.getKeyCode())
        {
            s1=true;
        }

        if(j==e.getKeyCode())
        {
            s2=true;
        }

        if(s1==true && s2==true)
        {
            System.out.println("EXIT NOW");
            System.exit(0);
        }
    }

    /** Handle the key released event from the text field. */

}

一般来说,您要描述的内容可以使用bitmasks来实现。

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

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