Java – how to use keylistener

I'm trying to implement a keylistener in my program so that when I press the arrow key, it will perform an action to move the objects in the program to the left or right

This is the mobile 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 want to know how the program should read (keyevent) e. I really can't enter an arrow key

Please help!

Edit: I also need to know that I need to add it to my code so that my program waits about 700 milliseconds for key input before going to another method

Solution

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

If it is a UI based application, then "I also need to know that I need to add it to my code so that my program waits for key input of about 700 milliseconds before going to another method." you can use glasspane or timer class to implement the requirement

For critical events:

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 out this game example http://zetcode.com/tutorials/javagamestutorial/movingsprites/

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>