JAVA项目学习之坦克大战图片版

坦克大战图片版即在单机版的基础上将画出的坦克改成一张张的图片,提高界面的美观性。

其关键是把硬盘上的图片读到内存再画出来

private int step = 0;
	/**
	 * 定义工具,不同操作系统的工具不同,其从硬盘读数据的方式可能不同
	 */
	private static Toolkit tk = Toolkit.getDefaultToolkit();
	/**
	 * 定义为静态,即载入内存中只保留一份
	 */
private static Image[] img = {
		/**
		 * 使用工具类读取硬盘上的文件,类类型获取装载器获得资源的url(反射)
		 */
		tk.getImage(Explode.class.getClassLoader().getResource("images/0.gif")),
		tk.getImage(Explode.class.getClassLoader().getResource("images/1.gif")),
		tk.getImage(Explode.class.getClassLoader().getResource("images/2.gif")),
		......
	};

注意static的用法,另外static还有一种灵活的用法如:

	static{
		Image[] img = {
				/**
				 * 使用工具类读取硬盘上的文件,类类型获取装载器获得资源的url(反射)
				 */
				tk.getImage(Tank.class.getClassLoader().getResource("images/tankL.gif")),
				tk.getImage(Tank.class.getClassLoader().getResource("images/tankLU.gif")),
				........
			};
		map.put(Direction.L, img[0]);
		map.put(Direction.LU, img[1]);
		........
	}


这样可以在中间加入代码

本项目介绍了配置文件类Properties的使用:首先需要添加*.properties的文件,里面写入一些配置信息,如tankcount=10(中间不能有空格,之后也不需要分号),然后可以调用Properties类中的load方法,载入流文件,代码如下:

Properties prop = new Properties();
try {
			prop.load(PropertyMgr.class
					.getResourceAsStream("property/tank.properties"));
		} catch (IOException e) {
			e.printStackTrace();
		}
int tankCount = Integer.parseInt(prop.getProperty("tankcount"));

本项目最后介绍了Singleton模式,即写一个配置的管理类,内存中只有一份对象实现对整个程序的配置管理,代码如下:

public class PropertyMgr {
	static Properties prop = new Properties();
	/**
	 * 写成静态内存中以有一份
	 */
	static {
		try {
			prop.load(PropertyMgr.class
					.getResourceAsStream("property/tank.properties"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 构造方法改成私有 使无法new新的PropertyMgr
	 */
	private PropertyMgr(){};
	public static String getProperty(String key) {
		return prop.getProperty(key);
	}
}



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值