Double buffer : Buffer Paint « 2D Graphics « Java Tutorial






Double buffer
import java.applet.Applet;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;

public class DoubleBufferWithBufferedImage extends Applet {
  int gap = 3;

  int mx, my;

  Image buffer = null;

  int w, h;

  public static void main(String[] a) {
    JFrame f = new JFrame();
    f.setSize(300, 300);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(new DoubleBufferWithBufferedImage());
    f.setVisible(true);
  }

  public DoubleBufferWithBufferedImage() {
    setSize(300, 300);
    Dimension d = getSize();
    w = d.width;
    h = d.height;
    buffer = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
  }

  public void paint(Graphics g) {
    Graphics screengc = null;

    screengc = g;

    g = buffer.getGraphics();

    g.setColor(Color.blue);
    g.fillRect(0, 0, w, h);

    g.setColor(Color.red);
    for (int i = 0; i < w; i += gap)
      g.drawLine(i, 0, w - i, h);
    for (int i = 0; i < h; i += gap)
      g.drawLine(0, i, w, h - i);
    screengc.drawImage(buffer, 0, 0, null);
  }
}








16.7.Buffer Paint
16.7.1.Off Screen Paint: create Graphics from BufferedImageOff Screen Paint: create Graphics from BufferedImage
16.7.2.Double bufferDouble buffer