本範例展示如何利用 Java Swing 依序讀取多張靜態圖片(JPG 格式),以固定幀率播放,形成類 GIF 動畫效果。適用於簡易遊戲過場動畫、教學演示等場合。
repaint()、睡眠控制幀率。package 靜態圖;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Donttai extends JFrame implements Runnable {
private final String basePath = "bin/靜態圖/花好月圓/10";
private int currentIndex = 1;
private static final int TOTAL_FRAMES = 16;
private static final int FRAME_DELAY_MS = 60;
public Donttai() {
initUI();
}
private void initUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600, 450);
setLocationRelativeTo(null);
setTitle("圖片序列動畫播放");
}
@Override
public void paint(Graphics g) {
super.paint(g);
String fileName = basePath + (currentIndex <= 9 ? "0" + currentIndex : currentIndex) + ".jpg";
try {
Image img = ImageIO.read(new File(fileName));
g.drawImage(img, 100, 50, 400, 300, new ImageObserver() {
@Override public boolean imageUpdate(Image img, int infoflags, int x, int y, int w, int h) {
return (infoflags & (ALLBITS | ABORT)) != 0;
}
});
} catch (IOException e) {
g.drawString("圖片載入失敗:" + fileName, 100, 100);
}
}
@Override
public void run() {
while (true) {
repaint();
currentIndex = (currentIndex % TOTAL_FRAMES) + 1;
try { Thread.sleep(FRAME_DELAY_MS); } catch (InterruptedException ignored) {}
}
}
public static void main(String[] args) {
Donttai player = new Donttai();
player.setVisible(true);
new Thread(player).start(); // 建議另開執行緒
}
}
BufferedImage 至 List,paint() 直接從記憶體取用,避免磁碟 I/O 卡頓。javax.swing.Timer 取代 Thread.sleep(),確保繪圖在 EDT 執行,符合 Swing 單執行緒規則。setDoubleBuffered(true)。