使用keyPressed检测键盘方向键 [英] Detecting keyboard direction keys using keyPressed

查看:1363
本文介绍了使用keyPressed检测键盘方向键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

G'day all,

G'day all,

在这里了解到Java控制台不支持键盘输入后,我转而使用Swing和AWT。我现在的问题是如何检测键盘方向键(非数字小键盘)的使用时间。按下向下,向上,向左,向右键时,我的代码(下面)不会打印小方块字符。例如,这个小方框字符与CTRL和ALT键使用的字符没有什么不同。有谁知道键盘方向键的实际身份是什么,以便我可以在我的应用程序中为它们编码?

After learning on here that the Java console doesn't support keyboard input a great deal, I switched to Swing and AWT. My problem now is how to detect when the keyboard direction keys (non-numeric keypad) are used. My code (below) does not do more than print a "small box" character when pressing the down, up, left, right keys. This small box character is no different from the character used by the CTRL and ALT keys, for example. Does anyone know what the identity of the keyboard direction keys actually is so that I can code for them in my application?

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class KeyChecker extends JFrame {
    JLabel keyLabel = new JLabel("Hit any key");

    public KeyChecker() {
        super("Hit a Key");
        setSize(300, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.CENTER));
        KeyMonitor monitor = new KeyMonitor(this);
        setFocusable(true);
        addKeyListener(monitor);
        add(keyLabel);
        setVisible(true);
    }

    public static void main(String[] arguments) {
        new KeyChecker();
    }
}

class KeyMonitor extends KeyAdapter {
    KeyChecker display;

    KeyMonitor(KeyChecker display) {
        this.display = display;
    }

    public void keyPressed(KeyEvent event) {
        display.keyLabel.setText("" + event.getKeyChar());
        display.repaint();
    }
}


推荐答案

什么你应该做的是在 keyPressed 中查看虚拟密钥代码而不是关键字符。像这样:

What you should do is look at the virtual key code rather than the key character, in keyPressed. Like so:

public void keyPressed(KeyEvent event) {
    switch (event.getKeyCode()) {
        case KeyEvent.VK_UP:
            // up arrow
            break;
        case KeyEvent.VK_DOWN:
            // down arrow
            break;
        case KeyEvent.VK_RIGHT:
            // right arrow
            break;
        case KeyEvent.VK_LEFT:
            // left arrow
            break;
    }
}

参见 http://java.sun.com/javase/6/docs/api/java/ awt / event / KeyEvent.html 获取完整信息。

这篇关于使用keyPressed检测键盘方向键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆