Java双缓冲绘图

方法一:

import java.awt.*;
import javax.swing.*;

public class skyplane {
    public static void main(String[] args) {

        JFrame w = new JFrame();
        w.setSize(824, 446);

        MyPanel mp = new MyPanel();
        w.add(mp);

        Thread t = new Thread(mp);
        t.start();

        w.show();

    }
}

class MyPanel extends JPanel implements Runnable {
    Graphics g1;
    Image buffer, plane, sky;
    int x = 10;
    int y = 400;

    public void paint(Graphics g) {
        super.paint(g);

        buffer = createImage(getWidth(), getHeight());// 创建图像缓冲区
        g1 = buffer.getGraphics(); //创建绘图区
        plane = new ImageIcon("image/plane.png").getImage(); //获取图像
        sky = new ImageIcon("image/sky.png").getImage(); //获取图像

        g1.drawImage(sky, 0, 0, this); //将图像先画到缓冲区
        g1.drawImage(plane, x, y, this); //将图像先画到缓冲区
        g.drawImage(buffer, 0, 0, this); //将缓冲区里的图像画出
    }

    public void run() {
        while (true) {
            if (x == 800)
                x = 10;
            else
                x += 2;
            if (y == 0)
                y = 400;
            else
                y--;
            try {
                Thread.sleep(50);
            } catch (Exception e) {
            }
            repaint();
        }
    }

}
 

方法二:

import java.applet.*;
import java.awt.*;

public class skyplane extends Applet {

    Image buffer, plane, sky;
    Graphics g1;
    Thread td;
    int x = 0;

    public void init() {
        this.setSize(824, 446);
        buffer = createImage(getWidth(), getHeight()); // 创建图像缓冲区
        g1 = buffer.getGraphics(); // 创建绘图区
        plane = getImage(getCodeBase(), "image/plane.png");
        sky = getImage(getCodeBase(), "image/sky.png");
    }

    public void paint(Graphics g) {
        g1.drawImage(sky, 0, 0, this);// 将图像先画到缓冲区
        g1.drawImage(plane, x, 20, this); // 将图像先画到缓冲区
        g.drawImage(buffer, 0, 0, this);
        try {
            Thread.sleep(50);
            x += 2;
            if (x == 800) {
                x = 2;
                Thread.sleep(50);
            }
        } catch (InterruptedException e) {
        }
        repaint();
    }

    public void update(Graphics g) {
        paint(g);
    }
}

 

posted on 2015-11-30 19:35  13rj1115  阅读(600)  评论(0编辑  收藏  举报

导航