简体   繁体   中英

What wrong with my code , I can't use KeyPressed method?

public void run() {
    setSize(700,700);
    setGame();
}
public GObject drawPlayer() {
    GOval player = new GOval(getWidth()/2,getHeight()/2,10,10);
    player.setFilled(true);
    player.setFillColor(Color.red);
    return player;
}
public void keyPressed(KeyEvent e) {
        switch(e.getKeyCode()) {
        case KeyEvent.VK_UP: Player.move(0, -10);break;
        case KeyEvent.VK_DOWN: Player.move(0, 10);break;
        case KeyEvent.VK_LEFT: Player.move(-10, 0);break;
        case KeyEvent.VK_RIGHT: Player.move(10, 0);break;
    }
}
public GRect object;
    public void setGame() {
    setObject();
    GObject Player = drawPlayer();
    add(Player);
    addKeyListeners();
}

I create the oval to player then, I addKeyListeners Method to detect key When I run I can't use the arrowkey to move the player object ?? What wrong with my code ???

Assuming that the above code is in a class which extends GraphicsProgram , that is valid code and should work as written. You are checking the correct key codes (although make sure they are not remapped somehow on your input device), you add addKeyListeners() correctly.

One gotcha is that the GraphicsProgram object has to have focus or else the keys will not be recognized. To test, you can start the program and immediately click in the applet window to grab focus. At this point, the keys should be recognized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM