java程序:为什么我按w、a、s、d就行,上下左右键不行?

图片说明

建议你调试一下,看看按上下左右键的键值是多少?
是不是按上下左右键压根就不进你这个 keyTyped 函数!


[code=Java]
public class OtherTest extends JFrame {
    private static final long serialVersionUID = 1L;

    public static void main(String[] args) {
        MyPanel mp = new MyPanel();
        OtherTest ot = new OtherTest();
        ot.add(mp);
        ot.addKeyListener(mp); 
        ot.setSize(400, 300);
        ot.setTitle("Moving XO");
        ot.setLocationRelativeTo(null);
        ot.setVisible(true);
    }
}

class MyPanel extends JPanel implements KeyListener {
    private static final long serialVersionUID = 1L;
    int x = 10;
    int y = 10;

    public void paint(Graphics g) {
        super.paint(g);
        g.fillOval(x, y, 10, 10);
    }

    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_DOWN) {
            y++;
        } else if (e.getKeyCode() == KeyEvent.VK_UP) {
            y--;
        } else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            x--;
        } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            x++;
        }
        this.repaint();
    }

    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub

    }

    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub

    }

}

方法判断上没有什么问题。

你看看到底是什么值啊,调试看看

debug发现e.getKeyCode()都是0.
getKeyCode()是类 KeyEvent的方法,API是这么说的

getKeyCode
public int getKeyCode()返回与此事件中的键关联的整数 keyCode。
返回:
键盘上实际键的整数代码。(**对于 KEY_TYPED 事件,该 keyCode 为 VK_UNDEFINED。**)

keyTyped方法换成keyPressed方法,亲测有效

恩,debug是个好东西,都为0 ,肯定就无法判断准确了

下面是关于keyTyped的解释,简单的说一下就是,type是高级事件,不是所有的按键都能产生keyTyped事件的,比如你说的上下左右四个键,因为他不能生成一个正确的Unicode character,因此是无法进行识别的。而其他两个事件press和release是没有这个限制的,他们是低级别的事件,因此可以用他们进行代替。

"Key typed" events are higher-level and generally do not depend on the platform or keyboard layout. They are generated when a Unicode character is entered, and are the preferred way to find out about character input. In the simplest case, a key typed event is produced by a single key press (e.g., 'a'). Often, however, characters are produced by series of key presses (e.g., 'shift' + 'a'), and the mapping from key pressed events to key typed events may be many-to-one or many-to-many. Key releases are not usually necessary to generate a key typed event, but there are some cases where the key typed event is not generated until a key is released (e.g., entering ASCII sequences via the Alt-Numpad method in Windows). No key typed events are generated for keys that don't generate Unicode characters (e.g., action keys, modifier keys, etc.).