天天看点

jtable中加载动态图片

   在JTable中添加静态图片已经是处处可见的示例了,有些时候,在JTable获取数据的时候,耗时比较长,我们会采用线程的方式加载数据,在这个过程中为了提升用户体验,会在JTable中添加等待的动态图片直到数据加载完毕。如果使用添加静态图片的方式,会发现效果是动态图片一直停在那里不动,就好像一个静态图片,失去了想要的效果。

   要实现动态图片的添加,就必须为ImageIcon添加一个实现了ImageObserver接口的观察者,由他来处理动态图片的动态变化,然后通知JTable调用updateUI进行更新

public class MyImageObserver implements ImageObserver {

	JTable table;
	int row;
	int col;
	
	public MyImageObserver(JTable table,int row, int col){
		this.table = table;
		this.row = row;
		this.col = col;
	}

	public boolean imageUpdate(Image img, int infoflags, int x, int y,
			int width, int height) {
		// TODO Auto-generated method stub
		if ((infoflags & (FRAMEBITS | ALLBITS)) != 0) {
	        Rectangle rect = table.getCellRect(row, col, false);
	        table.repaint(rect);
	      }
		return (infoflags & (ALLBITS | ABORT)) == 0;

	}

}
           

    ImageIcon只需调用setImageObserver方法即可:

ImageIcon icon = new ImageIcon(com.test.ui.images.GetIcons.class.getResource("loading2.gif"));
icon.setImageObserver(new MyImageObserver(getTable(),i,0));
           

继续阅读