简体   繁体   English

我的代码有什么问题,我不能使用KeyPressed方法?

[英]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.

相关问题 为什么我的代码没有进入keyPressed()方法? (即使我按了键) - Why doesn't my code go in the keyPressed() method? (Even if i press keys) 我的代码有什么问题? 我无法打印条形码或二维码 - What is wrong with my code? I can't print a Barcode or a Qrcode 我无法在我的代码中使用 findOne() 方法 - I can't use findOne() method in my code 为什么我的servlet代码中不能使用doGet方法? - Why can't i use doGet method in my servlet code? 我在 Java 中的方法找不到变量的值并将其设置为 0。我做错了什么? - My method in Java can't find the value of the variable and sets it as 0. What am I doing wrong? 如何避免 keyPressed 方法使我的绘图在处理 3 中永久存在? - How can I avoid keyPressed method to make my draw permenant in Processing 3? 我的代码有什么问题,因此无法播放wav文件? - What is wrong with my code so it can't play wav file? 无法弄清楚我的合并排序代码有什么问题 - Can't figure out what is wrong with my merge sort code 如果run()方法中的if语句为true,为什么我不能再使用keyPressed? - Why can't i use keyPressed anymore once the if-statement is true in the run()-methode? KeyListener-我是否需要在主程序中调用keyPressed方法? - KeyListener - do I need to call the keyPressed Method in my main?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM