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

问题描述

在java中我有一个程序需要连续检查用户是否按了一个键。
所以在psuedocode中,类似于

In java I have a program that needs to check continuously if a user is pressing a key.So In psuedocode, somthing like

if (isPressing("w"))
{
 //do somthing
}

提前致谢!

推荐答案

在java中你不会检查是否按下了某个键,而是 listen KeyEvent 秒。
实现目标的正确方法是注册 KeyEventDispatcher ,并实现它以维持所需密钥的状态:

In java you don't check if a key is pressed, instead you listen to KeyEvents.The right way to achieve your goal is to register a KeyEventDispatcher, and implement it to maintain the state of the desired key:

import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;

public class IsKeyPressed {
    private static volatile boolean wPressed = false;
    public static boolean isWPressed() {
        synchronized (IsKeyPressed.class) {
            return wPressed;
        }
    }

    public static void main(String[] args) {
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {

            @Override
            public boolean dispatchKeyEvent(KeyEvent ke) {
                synchronized (IsKeyPressed.class) {
                    switch (ke.getID()) {
                    case KeyEvent.KEY_PRESSED:
                        if (ke.getKeyCode() == KeyEvent.VK_W) {
                            wPressed = true;
                        }
                        break;

                    case KeyEvent.KEY_RELEASED:
                        if (ke.getKeyCode() == KeyEvent.VK_W) {
                            wPressed = false;
                        }
                        break;
                    }
                    return false;
                }
            }
        });
    }
}

然后你可以随时使用:

if (IsKeyPressed.isWPressed()) {
    // do your thing.
}

当然,您可以使用相同的方法来实现 isPressing(< some key>)带有键的映射及其状态包含在 IsKeyPressed 中。

You can, of course, use same method to implement isPressing("<some key>") with a map of keys and their state wrapped inside IsKeyPressed.

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

08-21 01:19