how can I detect arrow keys in java?

2019-03-16 07:28发布

问题:

I know how to implement a key listener; that's not the problem.

public void keyTyped(KeyEvent event) {
    if (event.getKeyChar() == KEY_LEFT) {
        cTDirection = LEFT;
    }
    if (event.getKeyChar() == 40) {
        cTDirection = DOWN;
    }
    if (event.getKeyChar() == 39) {
        cTDirection = RIGHT;
    }
    if (event.getKeyChar() == 38) {
        cTDirection = UP;
    }
}

What do I put where the LEFT_KEY / 40 / 39 / 38? When I created a keylistener and type in the keys, I believe I got 37 - 40. I don't know what to put there to listen for just the arrow keys.

回答1:

I would recommend using:

if (event.getKeyCode() == KeyEvent.VK_UP) {
...
}

repeating with VK_DOWN, VK_LEFT, VK_RIGHT.

There are seperate codes for the numeric keypad: VK_KP_UP, VK_KP_DOWN, VK_KP_LEFT, VK_KP_RIGHT if you need them.

See KeyEvent for all of the codes.



回答2:

KeyEvent.VK_LEFT, KeyEvent.VK_RIGHT, etc.

Also, you should use getKeyCode, not getKeyChar. getKeyChar is for keys that actually correspond to characters (letters, numbers, spaces, etc.).



回答3:

Use

if ( e.getKeyCode() == KeyEvent.VK_LEFT){
     //Do something
}

The other keys are:

KeyEvent.VK_UP

KeyEvent.VK_RIGHT

KeyEvent.VK_DOWN



回答4:

Here is what I did to make it work:

public void keyPressed (KeyEvent e) {
        int c = e.getKeyCode ();
        if (c==KeyEvent.VK_UP) {                
            b.y--;   
        } else if(c==KeyEvent.VK_DOWN) {                
            b.y++;   
        } else if(c==KeyEvent.VK_LEFT) {                
            b.x--;   
        } else if(c==KeyEvent.VK_RIGHT) {                
            b.x++;   
        }
        System.out.println (b.x);
        b.repaint ();
    }

For me it isn't working if I put it in KeyPressed but works fine if I put it in KeyTyped.



回答5:

Use the getKeyCode() method and compare the returned value agains KeyEvent.VK_LEFT, KeyEvent.VK_RIGHT, KeyEvent.VK_UP and KeyEvent.VK_DOWN constants.



回答6:

first declare init method

public void init(){

this.addKeyListener(new keyb());}

then use inner class which implements KeyListner

class keyb implements KeyListener{

    public void keyPressed (KeyEvent e){
    if(e.getKeyCode()==KeyEvent.VK_UP){
        y-=50;

    }else if(e.getKeyCode()==KeyEvent.VK_DOWN){
        y+=50;
    }else if(e.getKeyCode()==KeyEvent.VK_RIGHT){            
        x+=50;
    }else if(e.getKeyCode()==KeyEvent.VK_LEFT){
        x-=50;
    }

    repaint();

    }
    public void keyReleased (KeyEvent e){}
    public void keyTyped (KeyEvent e){}
    }

you can also use adapter instead of writing Keyreleased & keyTyped .... as you know



回答7:

btw in KeyAdapter -> keyTyped getCharCode() didn't work You should try keyPressed or keyReleased