大家好我有一个学校项目,我需要帮助实现java keylistener函数。现在我用鼠标监听器做了它,但被要求用箭头键进行移动。 这是我的课程。
SpaceShipGame.java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.util.Random;
public class Asteroid {
private int xPos;
private int yPos;
private static int height = 30; //height of the asteroid
private static int width = 35; //width of the asteroid
public Asteroid(int x, int y)
{
Random r = new Random();
xPos = 800 + r.nextInt(50); //initial x position of the asteroid
yPos = 50 + r.nextInt(700); //initial y position of the asteroid
}
public void move() {
xPos = xPos - 15; //move the asteroid to the left by 15
}
public void draw(Graphics g) {
g.setColor(Color.gray);
g.fillOval(xPos, yPos, width, height); //draws the asteroid as a gray oval
}
public Point getPosition() {
return new Point(xPos, yPos); //returns the position of the asteroid
}
}
这是SpaceShip.java
{{1}}
Asteroid.java
{{1}}
尝试使用左右箭头键在x方向上移动平台对象。在使用一些println语句测试之后,keyPressed方法的if条件工作,但我无法使用keyListener移动平台对象。是与Platform类中的moveLeft,moveRight方法有关,因为我试图改变dx的值,所以我可能会看到平台中的一些动作。我也尝试用键盘按钮进行拍摄,但没有成功。在此先感谢您的帮助