简体   繁体   English

Java-KeyListener不起作用

[英]Java - KeyListener not working

This has been making me want to tear out my hair all day. 这一直让我想整天撕掉头发。 I'm trying to make it so when I press the right-arrow key, my speed will go to 10. I know that my methods that make my sprite move work, because if I set a value beforehand, it moves across the screen. 我正在尝试这样做,因此当我按下右箭头键时,速度将达到10。我知道使我的精灵移动的方法可以工作,因为如果事先设置一个值,它将在屏幕上移动。 It's the KeyListener that isn't doing anything: 是KeyListener没有执行任何操作:

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;

public class Sprite implements KeyListener{
    public Image player = Toolkit.getDefaultToolkit().getImage("player.png");
    int x, y, dx, dy;

    public void doInit(){
        JFrame window = new JFrame();
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setSize(600, 400);
        window.setLocationRelativeTo(null);
        window.getContentPane().add(new ImageDraw());
        window.setVisible(true);
        window.setIgnoreRepaint(true);
        window.createBufferStrategy(2);
        window.getContentPane().addKeyListener(this);
    }

    public Image getSpriteHandle(){
        return player;
    }

    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();
        if(keyCode == KeyEvent.VK_RIGHT){
                dx = 10;
         }
    }   //end keyPressed

    public void keyReleased(KeyEvent e) {
        int keyCode = e.getKeyCode();
        if(keyCode == KeyEvent.VK_RIGHT){
                dx = 0;
         }
    }

    public void keyTyped(KeyEvent arg0) {

    } 

    public int moveX(){
        return dx;
    }

}   //end class

Please help me! 请帮我!

It's the KeyListener that isn't doing anything 是KeyListener没有做任何事情

You should NOT be using a KeyListener. 您不应该使用KeyListener。

Swing was designed to be used with Key Bindings . Swing被设计为与键绑定一起使用。 You can map an Action to a KeyStroke even when a component doesn't have focus. 即使组件没有焦点,也可以将Action映射到KeyStroke。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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