java中的双缓冲技术

2008-07-25 14:55:06.0     浏览:659     来源:中国IT实验室
关键词:  java     双缓冲  

毕业设计有个远程协助功能,得到对方的屏幕后,老是会闪,很是不爽,今天用java的双缓冲技术解决了。代码如下,本类重写了Swing中的JLabel,当Label重绘时,会默认的调用它的update方法,主要用于清除界面,然后update方法会调用paint方法,再把界面画上去,所以我现在update方法中创建了一个Image和Graphics对象Image off_screen_buf和off_screen_gc同时设置其大小和MyLabel对象的大小一样,用于把要画的东东先绘制到后台内存中,然后调用paint方法把要画的图像画在上面。最后再把内存中的图像画在前台上用off_screen_buf作为参数。再调用repaint方法,repaint方法回默认的调用update方法,这样图像就能够不停的显示了。

public class MyLabel extends JLabel

{

//双缓冲技术

private Image off_screen_buf;

private Graphics off_screen_gc;

public void paint(Graphics g)

{
if(Myjxta.image!=null)

{

this.setPreferredSize(new Dimension(Myjxta.image.getWidth(),Myjxta.image.getHeight()));

g.drawImage(Myjxta.image, 0, 0, this);

}
try

{

Thread.sleep(200);

}

catch(Exception e)

{

e.printStackTrace();

}

}

public void update(Graphics g)

{

if (Myjxta.image != null)

{

off_screen_buf =this.createImage(this.getWidth(),this.getHeight());

off_screen_gc = off_screen_buf.getGraphics();

paint(off_screen_gc);

off_screen_gc.dispose();

g.drawImage(off_screen_buf,0,0,null);

this.repaint() ;

}

}

}