功能:使用双缓冲消除闪烁现象(消除闪烁是应该的,不过处理有点不太好理解)
方法:将是所有的图像都画在虚拟图片上面然后显示出来。
关键代码:
Image offScreenImage = null;
public void update(Graphics g) {
if(offScreenImage == null){
offScreenImage = this.createImage(800,600);
}
Graphics gOffScreen = offScreenImage.getGraphics();
Color c = gOffScreen.getColor();
gOffScreen.setColor(Color.GREEN);
gOffScreen.fillRect(0, 0, 800, 600);
gOffScreen.setColor(c);
print(gOffScreen);
g.drawImage(offScreenImage, 0, 0, null);
}
Graphics gOffScreen = offScreenImage.getGraphics();
全部代码:
public class TankClient extends Frame {
int x = 30; int y = 30; //定义在方法外面
Image offScreenImage = null;
public void paint(Graphics g) {
Color c = g.getColor();
g.setColor(Color.RED);
g.fillOval(x, y, 30, 40);
g.setColor(c);
y += 5;
}
public void update(Graphics g) {
if(offScreenImage == null){
offScreenImage = this.createImage(800,600);
}
Graphics gOffScreen = offScreenImage.getGraphics();
Color c = gOffScreen.getColor();
gOffScreen.setColor(Color.GREEN);
gOffScreen.fillRect(0, 0, 800, 600);
gOffScreen.setColor(c);
print(gOffScreen);
g.drawImage(offScreenImage, 0, 0, null);
}
public void lauchFrame(){
this.setSize(800,600);
this.setTitle("TankWar");
this.setLocation(80, 60);
this.setVisible(true);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
this.setResizable(false);
new Thread(new paintThread()).start();
}
public static void main(String[] args) {
TankClient tc = new TankClient();
tc.lauchFrame();
}
private class paintThread implements Runnable { //线程 内部类 为此线程服务
public void run() {
while(true){
repaint();
try {
Thread.sleep(50);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}