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 addaddKeyListeners()
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.