[英]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 ?? 然后,我为播放器创建了一个椭圆形,我使用addKeyListeners方法检测键。运行时,我无法使用arrowkey移动播放器对象? 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. 假设上面的代码在扩展
GraphicsProgram
的类中,那是有效的代码,应按编写的方式工作。 You are checking the correct key codes (although make sure they are not remapped somehow on your input device), you add addKeyListeners()
correctly. 您正在检查正确的键代码(尽管确保它们在输入设备上未以某种方式重新映射),但是您正确添加了
addKeyListeners()
。
One gotcha is that the GraphicsProgram
object has to have focus or else the keys will not be recognized. 一个难题是
GraphicsProgram
对象必须具有焦点,否则键将无法识别。 To test, you can start the program and immediately click in the applet window to grab focus. 要进行测试,您可以启动该程序,然后立即在applet窗口中单击以获取焦点。 At this point, the keys should be recognized.
此时,应该识别密钥。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.