Use buffer to draw, draw to a BufferedImage first, then paint the whole image in Java
Description
The following code shows how to use buffer to draw, draw to a BufferedImage first, then paint the whole image.
Example
import java.applet.Applet;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
//from w w w. j a va2s . c o m
import javax.swing.JFrame;
public class Main 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 Main());
f.setVisible(true);
}
public Main() {
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);
}
}
The code above generates the following result.