Webber: A Website Construction Application


GraphicsBuffer.java


// Implementation of a double-buffer for a Component Graphics context

package library;

import java.awt.*;

public class GraphicsBuffer {
	private Component c;
	private Rectangle r;
	private Graphics g;
	private Image i;

	// Return the visible or clipped area of a component
	private Rectangle getImageArea(Component c, Graphics g) {
		Rectangle r;
		if ((r = g.getClipBounds())==null) {	// Get clipped area (if any)
			Dimension d = c.getSize();	// Use component size
			r = new Rectangle(0, 0, d.width, d.height);
		}
		return r;
	}

	// Return a new hidden Graphics context for a component
	public Graphics getGraphics(Component c) {
		return getGraphics(c, c.getGraphics());
	}
	public Graphics getGraphics(Component c, Graphics g) {
		return getGraphics(c, getImageArea(c, g), g);
	}
	public Graphics getGraphics(Component c, Rectangle r, Graphics g) {
		this.c = c;
		this.r = r;
		this.g = g;
		i = c.createImage(r.width, r.height);	// Create the Image buffer
		g = i.getGraphics();			// Get Graphics for Image
		g.translate(-r.x, -r.y);		// Translate clipped origin
		return g;
	}

	// Paint the contents of the image buffer
	public void paint() { g.drawImage(i, r.x, r.y, c); }
	public void paint(int xoff, int yoff) { g.drawImage(i, r.x+xoff, r.y+yoff, c); }

	// Crop an image painted with offsets
	public void crop(int xoff, int yoff) { crop(xoff, yoff, c.getBackground()); }
	public void crop(int xoff, int yoff, Color color) {
		Rectangle view = getImageArea(c, g);
		Color col = g.getColor();
		g.setColor(color);
		int i = (r.x + xoff) - view.x;
		if (i > 0)	// Clear left border
			g.fillRect(view.x, view.y, i, view.height);

		i = (view.x + view.width) - (r.x + r.width + xoff);
		if (i > 0)	// Clear right border
			g.fillRect(view.x + view.width - i, view.y, i, view.height);

		i = (r.y + yoff) - view.y;
		if (i > 0)	// Clear top border
			g.fillRect(view.x, view.y, view.width, i);

		i = (view.y + view.height) - (r.y + r.height + yoff);
		if (i > 0)	// Clear bottom border
			g.fillRect(view.x, view.y + view.height - i, view.width, i);
		g.setColor(col);
	}
}

Go To: Source Code