java实现动态图片效果
源码
package forGame;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class Demo_1 extends JFrame{
private BufferedImage bufferedImage;
private int width;
private int height;
private BufferedImage[] images = new BufferedImage[4];
private BufferedImage image;
{
if(bufferedImage == null){
try {
bufferedImage = ImageIO.read(new File("src\\image\\背景.png"));
for(int i = 1;i < images.length + 1;i ++)
images[i - 1] = ImageIO.read(new File("src\\image\\大飞机爆炸" + i + ".png"));
} catch (IOException e) {
e.printStackTrace();
}
}
width = bufferedImage.getWidth();
height = bufferedImage.getHeight();
image = images[0];
}
public Demo_1(){
super("动态测试");
setSize(width,height);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
MyThread myThread = new MyThread();
myThread.start();
}
@Override
public void paint(Graphics g) {
Image image = this.createImage(width,height);
Graphics gImage = image.getGraphics();
gImage.setColor(gImage.getColor());
gImage.fillRect(0,0,width,height);
super.paint(gImage);
gImage.drawImage(bufferedImage,0 ,0 ,null );
gImage.drawImage(this.image,0 ,100 ,null );
g.drawImage(image,0 ,0 , null);
}
private int num = 0;
private class MyThread extends Thread{
@Override
public void run() {
while(true) {
if(num <= 3) {
image = images[num ++];
}
else
num = 0;
repaint();
try {
sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
new Demo_1();
}
}
效果图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7e3d05d34bf154dcc656bc6dbfc319f3.png#pic_center)