I am pasting the whole TexturedComponentUtil class here.
******************************************************
package fr.ui;
import java.awt.*;
import javax.swing.*;
public final class TextureComponentUtil {
/**
* Tiles a texture across a range
* @param g the graphics object used for drawing
* @param component the component that needs to be drawn
* @param bgImage the texture
* @param x1 the starting x location, which may be negative
* @param y1 the starting y location, which may be negative
* @param x2 the ending x location, which must be larger than x1
* @param y2 the ending y location, which must be larger than y2
*/
public static final void drawTexturedBackground(Graphics g, Component component, Image bgImage, int x1, int y1, int x2, int y2) {
if (g == null || component == null || bgImage == null) {throw new NullPointerException();}
if (x2 < x1 || y2 < y1) {return;}
int imageWidth = bgImage.getWidth(component), imageHeight = bgImage.getHeight(component);
// the number of complete rows and columns
int numX = (x2-x1)/imageWidth;
int numY = (y2-y1)/imageWidth;
// start at left
int drawX = x1;
// get everything across until the last incomplete column
for (int x = 0; x<numX; x++) {
// start at top
int drawY = y1;
for (int y=0; y<numY; y++) {
g.drawImage(bgImage, drawX, drawY, component);
// move down one space
drawY += imageHeight;
}
// this completes the column
g.drawImage(bgImage, drawX, drawY, drawX+imageWidth, y2, 0,0, imageWidth, y2-drawY, component);
drawX += imageWidth;
}
// get the last column except for the last little box
int drawY = y1;
for (int y=0; y<numY; y++) {
g.drawImage(bgImage, drawX, drawY, x2, drawY+imageHeight, 0, 0, x2-drawX, imageHeight, component);
drawY+= imageHeight;
}
// now draw whatever is leftover, which is smaller than one texture unit
g.drawImage(bgImage, drawX, drawY, x2, y2, 0, 0, x2-drawX, y2-drawY, component);
}
/**
* Tiles a texture across a range
* @param g the graphics object used for drawing
* @param component the component that needs to be drawn
* @param bgImage the texture
*/
public static final void drawTexturedBackground(Graphics g, JComponent component, Image bgImage) {
drawTexturedBackground(g, component, bgImage, 0, 0, component.getWidth(), component.getHeight());
}
}