TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
首先你需要知道的是,如果你是在一个Swing组件上作图的话,
Swing已经自动的为你实现了双缓冲,因此没有必要在这个问题上上脑筋了。
如果你使用的是AWT组件的话,你可以根据下面的流程使用双缓冲:
利用该组件之createImage()方法创建一个BufferedImage对象
利用BufferedImage的createGraphics()方法得到适当的Graphics对象
在得到的Graphics对象上作图
将做出的图形显示到该组件之Graphics对象上。
下面的代码片断实现了上述流程,其中g 是图形显示组件之Graphics对象。
Image bi = createImage(w, h);
Graphics big = bi.createGraphics();
// draw somthing
g.drawImage(bi, 0, 0, this);
关于双缓冲技术的详细内容,可以参考java Tutorial中的2D Graphics。
下面是一个使用双缓冲的例子,点击观看: import java.awt.*;
import java.applet.*;
public class sfish extends Applet implements Runnable{
int xpos=0;
Thread anime=null;
Image fish_img;
Image offscreen_buf=null;
int fish_width,fish_height;
public void init(){
fish_img=getImage(getCodeBase(),"images/fish.gif");
fish_width=60;
fish_height=80;
}
public void start(){
if(anime==null){
anime=new Thread(this);
anime.start();
}
}
public void paint(Graphics g){
g.drawImage(fish_img,xpos,50,this);
}
public boolean imageUpdate(Image img,int flage,int x,int y,int w,int h){
if(flage==ALLBITS){
Graphics g1=getGraphics();
paint(g1);
return false;
}
return true;
}
public void run(){
while(anime!=null){
if(offscreen_buf==null){
offscreen_buf=createImage(getSize().width,getSize().height);
}
Rectangle old_area=new Rectangle(xpos,50,fish_width,fish_height);
xpos+=10;
if(xpos>getSize().width)
xpos=0;
Rectangle new_area=new Rectangle(xpos,50,fish_width,fish_height);
Graphics offg=offscreen_buf.getGraphics();
offg.setColor(Color.white);
offg.fillRect(0,0,getSize().width,getSize().height);
paint(offg);
Graphics ong=getGraphics();
ong.drawImage(offscreen_buf,0,0,this);
try{
Thread.sleep(300);
}catch(InterruptedException e){};
}
}
}
[/code] |
|