Tiled Swing Components :: Alternative Approach.
You have seen on the previous page that using the fill() method wasn't the ideal way to make tiled backgrounds for swing components.
We also studied a snippet of code on the previous page that placed tiles manually on the background . The applet on your right hand side makes use of that code to paint the background image repeatedly across the components canvas. As you can see clearly there isn't a noticable improvement with this approach either.
The trouble with out approach is that if you are painting a back ground that's 100 tiles wide and 100 tiles long you end up looping 10,000 times. The iterations increase by an order of 2. So if you paint a 200 by 200 background you need 40,000 iterations.
We can reduce the number of iteration by first tiling in the horizontal direction, and then using that elongated tile to draw in the opposite direction. In other words instead of using a single tile, we first create a 'bar' and then place that bar to cover the entire area of the component. With this approach the time needed to repaint does not increase by an order of two.
The following snippet of code achieves this
public void paintComponent(Graphics g)
{
int x, y;
int width, height;
Rectangle clip = g.getClipBounds();
width = img.getHeight(this);
height = img.getWidth(this);
if(width > 0 && height > 0)
{
System.out.println("hello");
for(x = clip.x; x < (clip.x + clip.width) ; x += width)
{
for(y = clip.y; y < (clip.y + clip.height) ; y += height)
{
g.drawImage(img,x,y,this);
System.out.println(x +"," + y);
}
}
}
}
Well that's all for now folks, you can download the source and jar files for this article and try it on your own.

