Home E-Books Special Effects and Game Development in Java Images

Special Effects and Game Development in Java(TM) - Images

by Anibal Wainstein

4.0 Images

Java applets and applications can read two types of image formats, JPEG and GIF format. Java also support transparent GIF89 images, these images can get other images behind them to "shine through" the transparency pixels. Note that in spite of this an applet can never be made transparent, which means that you cannot have a transparent GIF89 image in an applet and at the same time get the homepage background to shine through. It is the ability to load images and to process or animate them, that makes Java applets to an alternative against GIF89 animations. When you, on top of this, are able to add interaction to these animations then it gets to be a very superior alternative. In this chapter we will review how to handle and how to work with images.

4.0.1 How to load and handle images in Java applets (the Image class)

It is the Image class that handles images. If an applet is going to load images then it needs to know where the image is and what the file is named. As we have mentioned in the last section, the images must be in JPEG or GIF87/89 format. You can load an image with the getImage() method:

public Image logo;
public void init()

The getImage() method requires two arguments: one is an URL to the location where the image is and the other argument is the name of the file in the form of a string. The getDocumentBase() method will return an URL object which is the location of the applet's class file. The applet will be able to load the image "logo.jpg" if it is in the same catalog as the class file. Later on in chapter 6, we will look more at the URL class. With this code the image can now be loaded. Please note that the image is not immediately fully read by the applet, this can lead to funny effects as you will see later. An image can later on be drawn with the Graphics method drawImage() in the following way:

public void paint(Graphics g)

There are several drawImage() methods, but the simplest is the one used in the code example here above. This method we will use extensively in the course. The arguments are an Image object, the x and y positions for the image and a reference to the applet itself (this). Click here to see how it works. Please note that the image should have the same dimensions as the applet.


Next Page >>