前几天有看到一个java awt程序,用的是线程控制雪花下落速度,实际效果偏差大,运行起来甚是晃眼。在网上查了一圈,发现解决画面闪烁问题的办法----双缓冲技术。双缓冲原理是先在内存中分配一个和窗口一样大的空间,然后利用getGraphics()方法去获得该空间并将它全部一次性的显示到屏幕上。调用情况是repaint() -> update(Graphics g) -> paint(Graphics g),实现起来也很简单,只需重写update方法,代码如下:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Panel;
import javax.swing.JFrame;
class Ppanel extends Panel {
private static final long serialVersionUID = 1L;
private int xx[] = new int[300];
private int yy[] = new int[300];
void sun() {
for (int i = 0; i < 300; i++) {
xx[i] = (int) (Math.random() * 800);
yy[i] = (int) (Math.random() * 800);
}
}
@Override
public void paint(final Graphics g) {
for (int i = 0; i < 300; i++) {
g.setFont(new Font("宋体", Font.BOLD, i % 10 + 20));
g.drawString("*", xx[i], yy[i]++);
if (yy[i] >= 800) {
yy[i] = 0;
}
repaint();
}
g.setColor(Color.WHITE);
this.setBackground(Color.BLACK);
}
@Override
public void update(Graphics g) {
Image offScreenImage = null;
if(offScreenImage==null){
//在内存中开辟一块绘图空间
offScreenImage = this.createImage(800, 800);
//获得这块绘图空间的画笔/绘图环境
Graphics goff=offScreenImage.getGraphics();
Color c=goff.getColor();
goff.setColor(Color.black);
//绘制背景
goff.fillRect(0, 0, 800, 800);
//画笔颜色还原
goff.setColor(c);
//绘制图案
paint(goff);
g.drawImage(offScreenImage, 0, 0, null);
}
}
}
public class TestStar {
public static void main(String[] args) {
JFrame jf = new JFrame();
Ppanel p = new Ppanel();
p.sun();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
jf.setSize(800, 800);
jf.add(p);
}
}