JAVA中解决双缓冲现象

代码如下:

import java.awt.*;
import java.awt.event.*;
public class TankClient extends Frame{
    int x=50;
    int y=50;
    Image offScreenImage=null;
    public void paint(Graphics g){
        Color c=g.getColor();
        g.setColor(Color.RED);
        g.fillOval(x, y, 30, 30);//fillOval()方法中参数是int整形
        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);
        paint(goffScreen);

        g.drawImage(offScreenImage, 0, 0, null);
    }
    public void LaunchFrame(){
        this.setLocation(50,50);
        this.setSize(800,600);
        this.setTitle("TankWar");
        this.addWindowListener(new WindowAdapter(){
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        this.setResizable(false);//窗口不可调节大小
        this.setBackground(Color.GREEN);
        this.setVisible(true);
        new Thread(new paintThread()).start();
    }
    public static void main(String[] args) {
        TankClient tk=new TankClient();
        tk.LaunchFrame();
    }
    private class paintThread implements Runnable{
        public void run(){
            while(true){
                repaint();//重量级中repaint首先调用update方法,update然后再调用paint方法。再轻量级组件中repaint直接调用paint方法
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }
    }

}

猜你喜欢

转载自blog.csdn.net/lpq1201/article/details/78487052