解决游戏界面闪烁的问题

在用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);//将缓冲图片粘贴到正面
	}
这便解决了闪烁的问题

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值