如何在Java中获取图形对象?

我正在做一个基本的太空入侵者游戏。 我从LWJGL .zip文件中获取了所有资源(我没有使用LWJGL库来创建我的游戏,只是从中获取图片等。)无论如何,每当我按下键盘上的“空格”时,我的KeyListener创建一个新的我的船发射的子弹。 但是,我不知道如何绘制项目符号图像,因为我的KeyListener没有传递图形对象,你需要一个绘制图像。 导致问题的代码是“Shot”构造函数中的“drawImage”方法。 inheritance我的代码:

public class KeyTyped{ public void keyESC(){ Screen.isRunning = false; } public void keyLEFT() { Screen.shipPosX -= 10; } public void keyRIGHT() { Screen.shipPosX += 10; } //This is automatically called from my KeyListener whenever i //press the spacebar public void keySPACE(){ if(!spacePressed){ ShotHandler.scheduleNewShot(); }else{ return; } } } 

公共类ShotHandler {

 public static int shotX = Screen.shipPosX; public static int shotY = Screen.shipPosY + 25; public static void scheduleNewShot() { //All this does is set a boolean to 'false', not allowing you to fire any more shots until a second has passed. new ShotScheduler(1); new Shot(25); } 

}

公共类Shot扩展了ShotHandler {

 public Shot(int par1){ //This is my own method to draw a image. The first parameter is the graphics object that i need to draw. GUI.drawImage(*????????*, "res/spaceinvaders/shot.gif", ShotHandler.shotX, ShotHandler.shotY); } //Dont worry about this, i was just testing something for(int i = 0; i <= par1; i++){ ShotHandler.shotY++; } } 

}

多谢你们! 任何帮助将不胜感激!

您需要在某处存储“bullet”的位置,然后在paintComponent(Graphics g)方法中访问该状态。 真的,这应该考虑很多。 让你的Shot类看起来像这样:

 public class Shot { private Point location; // Could be Point2D or whatever class you need public Shot(Point initLocation) { this.location = initLocation; } // Add getter and setter for location public void draw(Graphics g) { // put your drawing code here, based on location } } 

然后在你的按键方法中,

 public void keySPACE(){ // Add a new shot to a list or variable somewhere // WARNING: You're getting into multithreading territory. // You may want to use a synchronized list. yourJPanelVar.repaint(); } 

你将扩展JPanel并覆盖paintComponent

 public class GameScreen extends JPanel { public paintComponent(Graphics g) { for (shot : yourListOfShots) { shot.draw(g); } // And draw your ship and whatever else you need } } 

这是基本的想法。 希望现在有道理。 你Shot的绘图代码移到别处,但是为了简单起见,我只是坚持使用Shot类本身。

我会注意到我上面的内容是一些非常混乱的代码。 看看MVC模式。 它使得状态抽象更加清晰(将状态与显示代码分离)。

想法是听众应该改变游戏的状态 (即创建一个子弹,或改变子弹的位置,或其他),然后调用repaint() 。 然后Swing将调用paintComponent(Graphics g)方法,该方法将使用作为参数传递的Graphics绘制更新的游戏状态。