java实现gif播放(闪烁问题未解决)
import java.awt.Color; import java.awt.Event; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import java.awt.Window; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.rmi.CORBA.Util; import javax.swing.JFrame; public class MyGameFrame extends JFrame{ int num=0; int n=0; // 初始化 public void launchFrame() { this.setSize(1000, 800); this.setLocation(400, 100); this.setVisible(true); this.setBackground(new Color(num)); this.addWindowFocusListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { // TODO Auto-generated method stub System.exit(0); } }); new PaintThread().start();//启动线程 } @Override public void paint(Graphics g){ // 自动调用,绘制,图形,字体 Image png=GameUtil.getImage("images/"+num+".png");//png地址 g.drawImage(png, 250, 150, null); g.clearRect(0, 0, 1000, 1000); // g.fillRect(0, 0, 1000, 1000); num++; num=num%64; } class PaintThread extends Thread{ public void run() { while (true) { n++; System.out.println("更新第"+n+"次"); repaint(); try { Thread.sleep(60); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public static void main(String[] args) { MyGameFrame me=new MyGameFrame(); me.launchFrame(); } }
import java.awt.Image; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; public class GameUtil { private GameUtil() { } public static Image getImage(String path) { // TODO Auto-generated method stub BufferedImage image=null; try { URL url=GameUtil.class.getClassLoader().getResource(path); image=ImageIO.read(url); } catch (IOException e) { // TODO: handle exception e.printStackTrace(); } return image; } }
原理:
循环播放六十几帧png,用drawImage画出来
线程PaintThread控制每一帧停留时间然后重画
而png的命名是数字递增的
png文件
效果
png文件链接
链接: https://pan.baidu.com/s/1YaFRZBOV7uhM9BEETQOn5w 提取码: jfzt
更新时间2019-05-12 19:37:07
--------------------------------------------------------------------------------------------------
好奇一切知识的咸鱼<@_@>