通常让这些控件加载图片的代码如下:
JButton addTebBtn = new JButton(new ImageIcon(TabbedPanel.class
.getResource("/addTab.gif")));
如果要显示动态Gif图片这样做法就不灵了.如果要显示动态Gif图片的话,我们需要从JLabel,JButton等控件继承一个类,并重载其public void paint(Graphics g)方法,然后用一个线程不断去刷新它(用Timer也可以,请参考文章" 封装完毕,能显示当前时间并改变风格的菜单类 ( http://www.blogjava.net/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());
以上.