如何检查,如果用户按下一个键?如何检查,如果用户按下一个键?(How do I check if t

2019-05-08 17:20发布

在java中我有一个需要不断检查,如果用户按下一个键的程序。 所以在伪代码,像财产以后

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

提前致谢!

Answer 1:

在Java中,你不检查是否有键被按下,而不是你 KeyEvent秒。 实现你的目标,正确的方法是注册一个KeyEventDispatcher ,并执行它,以维持所需键的状态:

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



Answer 2:

试试这个:

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Main {

    public static void main(String[] argv) throws Exception {

    JTextField textField = new JTextField();

    textField.addKeyListener(new Keychecker());

    JFrame jframe = new JFrame();

    jframe.add(textField);

    jframe.setSize(400, 350);

    jframe.setVisible(true);

}

class Keychecker extends KeyAdapter {

     @Override
     public void keyPressed(KeyEvent event) {

     char ch = event.getKeyChar();

     System.out.println(event.getKeyChar());

}


Answer 3:

你必须实现KeyListener这里,我们来看一看: http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyListener.html

:关于如何使用它的更多细节http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html



文章来源: How do I check if the user is pressing a key?
标签: java input key