通常讓這些控件加載圖片的代碼如下:
JButton addTebBtn = new JButton(new ImageIcon(TabbedPanel.class
.getResource("/addTab.gif")));
如果要顯示動態Gif圖片這樣做法就不靈了.如果要顯示動態Gif圖片的話,我們需要從JLabel,JButton等控件繼承一個類,并重載其public void paint(Graphics g)方法,然后用一個線程不斷去刷新它(用Timer也可以,請參考文章" 封裝完畢,能顯示當前時間并改變風格的菜單類 ( http://www.tkk7.com/sitinspring/archive/2007/06/08/122753.html )"中Timer 的做法,它有少實現一個Runnable接口的優勢),這樣gif的動態效果就顯示出來了.
標簽的完整代碼如下,其它控件大家可自行參照實現:
package com.junglesong.common.component.label;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;

import javax.swing.JLabel;


public class DynGifLabel extends JLabel implements Runnable
{
private static final long serialVersionUID = 45345345355L;

// 用以存儲Gif動態圖片
public Image image;

// 用以刷新paint函數
Thread refreshThread;


/** *//**
*
* @param image:
* Sample:new ImageIcon(DynGifLabel.class
* .getResource("/picture.gif")).getImage()
*/

public DynGifLabel(Image image)
{
this.image = image;
refreshThread = new Thread(this);
refreshThread.start();
}


/** *//**
* 重載paint函數
*/

public void paint(Graphics g)
{
super.paint(g);
Graphics2D graph = (Graphics2D) g;

if (image != null)
{
// 全屏描繪圖片
graph.drawImage(image, 0, 0, getWidth(), getHeight(), 0, 0, image
.getWidth(null), image.getHeight(null), null);
}
}


/** *//**
* 隔100毫秒刷新一次
*/

public void run()
{

while (true)
{
this.repaint();// 這里調用了Paint

try
{
Thread.sleep(100);// 休眠100毫秒

} catch (Exception e)
{
e.printStackTrace();
}
}
}
}
使用過程如下:
DynGifLabel stateLbl = new DynGifLabel(new ImageIcon(ThreadPanel.class
.getResource("/startThread.gif")).getImage());
以上.