Jump to Real's How-to Main page

Use an Image as the Applet background

import java.applet.Applet; 
import java.net.*;

//  TILE BACKGROUND
//     in the HTML use :
//       PARAM NAME="bgImage" VALUE="images/myImage.jpg"
//     in the APPLET tag

public class Tile extends Applet { 
  Image bgImage = null; 

  public void init() { 
   try { 
      MediaTracker tracker = new MediaTracker (this);
      bgImage = getImage
        (new URL(getCodeBase(), getParameter("bgImage"))); 
      tracker.addImage (bgImage, 0);
      tracker.waitForAll();
   }
   catch (Exception e) { 
      e.printStackTrace();
   }
   setLayout(new FlowLayout());
   add(new Button("Ok"));
   add(new TextField(10));
  } 

  public void update( Graphics g) { 
   paint(g); 
  } 

  public void paint(Graphics g) { 
   if(bgImage != null) { 
      int x = 0, y = 0; 
      while(y < size().height) { 
         x = 0; 
         while(x< size().width) { 
            g.drawImage(bgImage, x, y, this); 
            x=x+bgImage.getWidth(null); 
            } 
         y=y+bgImage.getHeight(null); 
      } 
   } 
   else {
      g.clearRect(0, 0, size().width, size().height); 
   } 
  } 
}

<HTML>
  <TABLE><TR><TD>
  <APPLET CODE=Tile.class WIDTH=150 HEIGHT=150>
    <PARAM NAME="bgImage"  VALUE="images/jht.gif">
  </APPLET>
</HMTL>
Try it here.
If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2005
[ home ]