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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/752999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:04:27  来源:igfitidea点击:

How do I handle simultaneous key presses in Java?

javaeventskeyboard

提问by Auras

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.

当我按住一个键(比方说向前移动)然后我按住另一个键(例如,向左转)时,会检测到新键,但不再检测到旧按键。

采纳答案by Michael Myers

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; when you get a keyReleased event, remove the key from the list.

当您收到 keyPressed 事件时,将新键添加到列表中;当您收到 keyReleased 事件时,从列表中删除该键。

Then in your game loop, you can do actions based on what's in the list of keys.

然后在您的游戏循环中,您可以根据键列表中的内容执行操作。

回答by Yuval Adam

Generally speaking, what you are describing can be achieved using bitmasks.

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

回答by Ganesh

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. */

}