How to use KeyListener

DSdavidDS picture DSdavidDS · Jun 4, 2012 · Viewed 210.5k times · Source

I am currently trying to implement a keylistener in my program so that it does an action when I pressed an arrow key, the object in my program either moves left or right.

Here is the moving method in my program

public void moveDirection(KeyEvent e)
    {
        int move = 0;
        int r = K.getRow();
        int c = K.getCol();
        if (e.getKeyCode() == 39) move = 1; //KeyEvent.VK_RIGHT
        if (e.getKeyCode() == 37) move = 2; //KeyEvent.VK_LEFT
        //if (e.getKeyCode() == KeyEvent.VK_DOWN) move = 3;

        switch (move)
        {
            case 1: if (inBound(r, c+1))
                        K.setLocation(r ,c+1); 
                    if (inBound(r, c-1) && frame2[r][c-1] == K)
                        frame2[K.getRow()][K.getCol()-1] = null; 
                    break; //move right 39
            case 2: K.setLocation(K.getRow(), K.getCol()-1); break; //move left 37
            //case 3: b.setLocation(b.getRow()+1, b.getCol()); break; //move down
            default: return;
        }        
        processBlockList();
    }

I am wondering how the program is supposed to read in (KeyEvent) e. I cannot really type in an arrowkey....

Please help!

edit: I also need to know what I need to add to my code so that my program waits about 700 milliseconds for a keyinput before moving on to another method

Answer

Abhishek Choudhary picture Abhishek Choudhary · Jun 4, 2012

http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html Check this tutorial

If it's a UI based application , then " I also need to know what I need to add to my code so that my program waits about 700 milliseconds for a keyinput before moving on to another method" you can use GlassPane or Timer class to fulfill the requirement.

For key Event:

public void keyPressed(KeyEvent e) {

    int key = e.getKeyCode();

    if (key == KeyEvent.VK_LEFT) {
        dx = -1;
    }

    if (key == KeyEvent.VK_RIGHT) {
        dx = 1;
    }

    if (key == KeyEvent.VK_UP) {
        dy = -1;
    }

    if (key == KeyEvent.VK_DOWN) {
        dy = 1;
    }
}

check this game example http://zetcode.com/tutorials/javagamestutorial/movingsprites/