运行,按下上键等,无反应.
求解决.
以下代码.
package cn.sst;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
public class GameUtil {
// 工具类最好将构造器私有化。
private GameUtil() {
}
public static Image getImage(String path) {
BufferedImage bi = null;
try {
URL u = GameUtil.class.getClassLoader().getResource(path);
bi = ImageIO.read(u);
} catch (IOException e) {
e.printStackTrace();
}
return bi;
}
}
package cn.sst;
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class MyGameFrame extends JFrame {
Image bgImg = GameUtil.getImage("images/bg.jpeg");
Image planeImg = GameUtil.getImage("images/plane.png");
Plane plane =new Plane(planeImg,250,250,5);
private Image offScreenImage = null;
public void update(Graphics g) {
if(offScreenImage == null)
offScreenImage = this.createImage(500,500);//这是游戏窗口的宽度和高度
Graphics gOff = offScreenImage.getGraphics();
paint(gOff);
g.drawImage(offScreenImage, 0, 0, null);
}
public void paint(Graphics g) {
g.drawImage(bgImg, 0, 0, null);
plane.drawSelf(g);
}
public static void main(String[] args) {
MyGameFrame f = new MyGameFrame();
f.launchFrame();
}
public void launchFrame() {
this.setTitle("123");
this.setVisible(true);
this.setSize(600, 600);
this.setLocation(700, 300);
////增加关闭窗口监听,这样用户点击右上角关闭图标,可以关闭游戏程序
this.addWindowListener(new WindowAdapter() {
public void Windowclosing(WindowEvent E) {
System.exit(0);
}
});
new PaintThread().start();
}
class PaintThread extends Thread {
public void run() {
while (true) {
repaint();
try {
Thread.sleep(40); //1s = 1000ms
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class KeyMonitor extends KeyAdapter{//定义键盘
@Override public void keyPressed(KeyEvent e) {
plane.adddirection(e);
}
@Override public void keyReleased(KeyEvent e) {
plane.minusdirection(e);
}
}
}
`
package cn.sst;
import java.awt.*;
public class GameObject {
Image img;
double x,y;
int speed;
int width,height;
public void drawSelf(Graphics g) {
g.drawImage(img,(int)x,(int)y,null);
}
public GameObject(Image img, double x, double y, int speed, int width, int height) {
super();
this.img = img;
this.x = x;
this.y = y;
this.speed = speed;
this.width = width;
this.height = height;
}
public GameObject(Image img, double x, double y) {
this.img = img;
this.x = x;
this.y = y;
}
public GameObject(Image img, double x, double y, int speed) {
this.img = img;
this.x = x;
this.y = y;
this.speed = speed;
}
public GameObject() {
}
}
![图片说明](https://img-ask.csdn.net/upload/201904/29/1556542340_634406.png)
![图片说明](https://img-ask.csdn.net/upload/201904/29/1556542351_280821.png)