Java cooperation home
Tutorial
type and press Enter

Using pictures in applets

Just like "adding" sound files to an applet you can add pictures. Now I want to explain to you how to do this by adding a background picture to our "ball bounce" applet. Again we have to declare a instance variable, an Image object called backImage:

    Image backImage;

Then we load a picture to our applet and store it in the object reference backImage (import java.applet.* and java.net.*!!). This works very similar to loading sound files, please add these lines to your init() - method:

    // load file Land.jpg
    backImgage = getImage (getCodeBase (), "Land.jpg");

As a last step we have to paint this picture in the paint() - method of the applet:

    // drawing the image: g.drawImage (name, x- value, y - value, frame)
    g.drawImage (backImage, 0, 0, this);

That's it! I used a *.jpg - file in this example but that is not that good. Normaly you should use *.gif - files, because their size is not that big (makes the applet run faster) and they are more common in the internet. An other reason to use *.gif - files is that you can define the background of a *.gif - file transparent. So you can use them to overlay for example a ball object (which is just a colored circle at the moment) with a real good looking picture. You can see a example for this in the game Streethockey and maybe there will be a "advanced topic" for this technique someday!

Sourcecode download
Take a look at the applet

Next chapter

Handling mouse events
Fabian Birzele, 2001-2004.
web-design: Vadim Murzagalin, 2004.