飞机大战设计基本流程
1.窗口显示 JFrame
2.画板/面板 JPanel
public static void main(String[] args) {
JFrame window = new JFrame("飞机大战"); //创建对象 并设定窗口的标题
GamePanel g = new GamePanel();
window.add(g);
g.action();
window.setSize(WIDTH, HEIGHT); //设置窗口的长宽
window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); //设置窗口的关闭
window.setLocationRelativeTo(null); //窗口居中
window.setVisible(true); //显示窗口
}
原生的 JPanel 中, 不能自定义绘画,只能画按钮, 输入框.. 等一些组件
功能加强 -> 自定义类继承 JPanel
3.图片读取
1.硬盘中有图片文件
2.将硬盘中的图片文件, 读取到JVM内存中, 成一个对象
InputOutput -> IO
类名.class -> 所有的类加载到方法区中,对应一个Class对象
通过重复使用一下语句,可以将图片读入内存中
airplane = ImageIO.read(FlyGame.class.getResourceAsStream("res/airplane.png"));
4.程序的设计
类的设计
飞机大战:
拥有相似的需求: 自己的飞机, 敌机, 小蜜蜂, 子弹
子类 extends 父类
自己的飞机: Hero
敌机: Airplane
小蜜蜂: Bee
子弹: Bullet - 有参的构造方法
大敌机: BigPlane
以上类中相同的成员变量, 和相同的方法, 提取出来
父类: FlyingObject
int x, int y, 图片, int width, int height
move() - 移动
5.补充父类中的构造方法
FlyingObject(int x, int y, BufferedImage img, int life) {
this.img = img;
this.width = img.getWidth();
this.height = img.getHeight();
this.x = x;
this.y = y;
this.life = life;
}
6.在主程序中创建各种对象进行测试测试