首先看效果图
使用到的四张图片
以下是实现此功能的代码
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();
}