Java小案例---奔跑的小猫

首先看效果图
小猫快跑

使用到的四张图片在这里插入图片描述 在这里插入图片描述 在这里插入图片描述 在这里插入图片描述

以下是实现此功能的代码
class RunningCat extends JFrame implements Runnable {

	/**
	 * 小猫的x轴坐标
	 */
	private int x = 10;
	/**
	 * 切换图片的索引
	 */
	private int i = 0; 
	/**  flag
	 * true 表示向右跑,false表示向左跑
	 */
	boolean flag = true; 
	
	/**
	 * 图片数组
	 * 	需要注意路径,此路径父目录是当前项目的所在位置, 如:在项目的src文件夹下则为,"src/CAT1.GIF"
	 */
	ImageIcon[] icon = {new ImageIcon("src/cn/jiutwo/report/CAT1.GIF"), new ImageIcon("src/cn/jiutwo/report/CAT2.GIF")}; // 向右跑图片
	ImageIcon[] icon2 = {new ImageIcon("src/cn/jiutwo/report/CAT3.GIF"), new ImageIcon("src/cn/jiutwo/report/CAT4.GIF")}; // 向左跑图片
	
	/**
	 * 初始化图形界面
	 */
	public RunningCat() {
		this.setBounds(10, 10, 400, 300);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setVisible(true);
	}

	/**
	 * 重写paint方法
	 */
	@Override
	public void paint(Graphics g) {
		super.paint(g);// 顶层容器重画
		g.drawLine(0, 200, 400, 200);
		if (flag) { //向右跑
			icon[i].paintIcon(this, g, x, 160);
		} else { // 向左跑
			icon2[i].paintIcon(this, g, x, 160);
		}
		
	}
	
	
	
	@Override
	public void run() {

		while (true) {
			x = x + 10; // 小猫的坐标
			// 0,1变换 ,切换图片
			i = (i + 1) % 2; 
			if (x >= 360) { // 到达边界,向左跑
				flag = false;
				while (true) {
					i = (i + 1) % 2;
					x -= 10;
					try {
						Thread.sleep(150);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					repaint();
					// 到达左边界,向右跑
					if (x <= 5) break; 
				}
				flag = true;
			}
			try {
				// 休眠,防止图片切换太快,一闪而过
				Thread.sleep(150); 
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			repaint();//每次改变后重画 ,调用了paint()方法
		}
	}
}

以下是启动上述线程的代码

	public static void main(String[] args) { 
		Thread thread = new Thread(new RunningCat());
		thread.start();
	}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值