Sorry you do not have the correct version of java installed.

Creating JPanel with tiled backgrounds.

What you see on the right is an applet that uses a tiled background image. It's based on the code that you have seen in the previous page. As you can see there is considerable lag in tiling the background. Should the area covered increase the lag would increase even more drastically.

So it would seem a solution which relies on the fill() method in Graphics2D isn't really suitable for production systems where the component might occupy the entire screen.

NOTE: The fact that painting is slow would be masked by the fact that there is a lag in loading the applet as well. Thus the delay in painting may not be apparent at first glance. You will be able to see it clearly if you scroll this page up and down rapidly. It would be more apparent if you just minimized and maximized your browser so that the entire applet becomes exposure damaged.

Even though it is never a good idea to re-invent the wheel, let's see if manual tiling will be any better. We can use a nested loop to draw the image repeatedly on the canvas. The code snippet below does just that.



	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);
				}
			}
		}
	}


You will see the revised version of the applet on the next page

.
Copyright © Raditha Dissanayake 2010