在用java编程的时候,我们处理窗口中物品移动的最常见的方法是使用paint方法不断重画,但是效果不好,会产生闪烁现象,如何解决呢?再次提出双缓冲的概念:
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TankClient extends Frame {
int x = 50;
int y = 50;
public void paint(Graphics g) {
Color c = g.getColor();
g.setColor(Color.RED);
g.fillOval(x, y, 30, 30);
g.setColor(c);
y+=5;
}
public void lauchFrame (){
this.setLocation(100, 100);
this.setSize(800, 600);
this.setTitle("TankWar");
this.setResizable(false);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
this.setBackground(Color.GREEN);
new Thread(new PaintThread()).start();
this.setVisible(true);
}
public static void main(String[] args) {
TankClient tc = new TankClient();
tc.lauchFrame();
}
private class PaintThread implements Runnable { //内部类
public void run() {
while(true){
repaint(); //使用的是外部包装类的paint()
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
在这段程序中,虽然小球在运动,但是屏幕不断闪烁,这是因为启用的线程类每50毫秒就刷新一次(调用repaint方法,repaint调用的是外部包装类的paint方法), 注意,这个 repaint()函数并不是我们重载的,而是从Frame类继承而来的。它先调用update(Graphics g)函数,update(Graphics g)再调用paint(Graphics g)函数 。
我们可以假设在这幅画的背面同样有一副画,我们每次都是画在背面的,然后用背面替代前面,这样就有了缓冲,但是怎么加这个背面的缓冲呢?重载paint方法不可能了,但是,我们可以重载中间的方法,即update方法。
public void update(Graphics g) {
if(offScreenImage == null){
offScreenImage = this.createImage(800, 600);
}
Graphics offScreen = offScreenImage.getGraphics();//首先要先拿到一只画笔
Color c = offScreen.getColor(); ///*这个地方的主要目的是解决原来小球的
offScreen.setColor(Color.GREEN); //位置没有被清除,因此小球的运动轨迹被
offScreen.fillRect(0, 0, 800, 600); //保留了下来,成为一条线,我们用背景色
offScreen.setColor(c); //同样颜色的方块覆盖掉原来的小球运动轨迹*/
paint(offScreen);
g.drawImage(offScreenImage, 0, 0, null);//将缓冲图片粘贴到正面
}
这便解决了闪烁的问题