0
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 ???

Robin Green
  • 32,079
  • 16
  • 104
  • 187
DrNutsu
  • 475
  • 2
  • 10
  • 21
  • 3
    You haven't included the source of "addKeyListeners". – Paul Tomblin Aug 02 '12 at 16:19
  • Did you mean `import java.awt.*;`?? Sorry, I'm already added but I didn't copy to this.. – DrNutsu Aug 06 '12 at 01:42
  • No, I mean that you call a method called `addKeyListeners` but don't show where you get it from. If it's a method in your class, you haven't shown it. If it's from an interface or class that you're implementing or extending, then you don't show us what class you're getting it from. It's not a documented method in any awt class that I can see. – Paul Tomblin Aug 06 '12 at 01:49
  • Oh..Sorry,I'm extends GraphicsProgram class. – DrNutsu Aug 07 '12 at 12:44

1 Answers1

0

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.

demongolem
  • 9,474
  • 36
  • 90
  • 105