Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

java - How to use KeyListener

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...