这让我想要整天撕掉我的头发。我正试图这样做,当我按下右箭头键时,我的速度将变为10.我知道我的方法使我的精灵移动工作,因为如果我事先设置一个值,它会在屏幕上移动。 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
请帮助我!
答案 0 :(得分:5)