java模拟落雪效果----双缓冲技术

      前几天有看到一个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);

	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值