Back Contents Next

Images and Animation

In this chapter we will introduce some of the basic techniques for reading images from a file and displaying them, and creating animation effects in your applications and applets. In this chapter you will learn:

 

q        How to read an image into an application or an applet

q        How to display an image

q        How to create animation effects

q        How to draw on an image

q        How to create an image internally to your program

q        What alpha compositing is

q        How to set the transparency of an image and create fading effects

 

We will use applets as the primary vehicle for working examples in this chapter, but don't forget that everything you will learn here can also be applied to your applications.

Applet Operations

We have already seen a few simple examples of applets, but we haven't really gone into how they are structured in any detail. Since we will be writing several rather more complicated applets in this chapter, we will remedy this right now.

 

To recap, an applet is defined by a class that has the Applet class as a base. We will use the Swing class JApplet which is derived from Applet to define our applets because it provides more capabilities. As you know, an applet is a program that is embedded in a web page, so it executes under the control of a web browser, or the appletviewer program that comes with the Java Development Kit. As we discussed in Chapter 1, you are likely to need to have the Java plug-in installed if Java 2 applets are to run with your browser. If you want to be sure that your applet will run with Netscape or Microsoft browsers without the plug-in being installed, then you must forgo the added capabilities of the JApplet class and limit yourself to using the Applet class as the base for your applet.

 

Whether an applet runs or not, and when it starts execution and when it stops, are all controlled by the browser, not by code in the applet. Of course, whether things work as they should still depends on the applet being implemented properly. When a browser loads a web page containing an applet, it will create an object of the class defining the applet. It will then use four methods for the applet class object to control the operation of the applet. All four methods are public, have a void return type and require no arguments. These methods are:

 

Method

Description

init()

To start your applet, the browser always calls the default constructor for your applet class to create the object, and then calls its init() method to do any initialization that is necessary. When init() is called, the applet is loaded and any parameters specified for the applet are available. You typically create any objects that are needed within the applet in this method and initialize any data members of the applet class. You will also implement the init() method to create any threads that the applet requires. Of course, your applet class can still have data members that you supply initial values for just like any other class. You can also implement the default constructor and do the initialization of data members there, too.

start()

This method is called by the browser to start or restart the operation of the applet. When the applet is started initially, the start() method will be called after the init() method has executed. The start() method is typically used to start any additional threads required in the applet. You don't always have to implement this method, but we will be using it a lot in this chapter to start animations.

stop()

This method is called when an applet should stop what it is doing temporarily – when the applet is 'hidden', for instance – because the user has scrolled the web page so the applet region is no longer visible. You would typically stop any continuously running operations that are in separate threads in this method – ones that might display an animation, for instance. This avoids wasting processor time on preparing images that can't be seen. To restart the applet the browser will call the start() method.

destroy()

This is called when the applet is being terminated so you should use it to free up any system resources that your applet uses. The stop() method is always called prior to this method being called.

 

The default implementations of these methods are inherited in your applet class, but they all do nothing. It is up to you to implement your versions of these methods so that they do what is necessary in the context of your applet. One other method that your applets should implement is getAppletInfo(). This method is expected to return a String object that contains information about the author, the version and copyright for the applet suitable for displaying in an "About" dialog.

 

The browser finds out about your applet through the HTML code that appears in the web page, so let's take a quick look at the bits that are likely to be involved.

HTML for Applets

In this section we will show HTML tags and attributes in upper case to highlight them, although they are not case sensitive. The basic HTML tags you need for embedding an applet in a web page are as follows:

 

<APPLET     CODE = "AppletName.class"

            WIDTH = "Applet_width_in_pixels"

            HEIGHT = "Applet_height_in_pixels" >

Optional alternate text displayed if the APPLET tag is not supported

</APPLET>

 

The optional default text after the APPLET tag is useful to signal when a browser does not support the APPLET tag – when the applet will not be executed. Other than that, the HTML tags above are the minimum required to include an applet in a page. The value for the CODE attribute in the APPLET tag identifies the .class file for the applet. This presumes the applet is in the same directory as the page containing the applet. If this is not the case you must not put the path as part of the CODE value. Instead, you should add a CODEBASE attribute that has a URL as a value that identifies the source for the applet – the URL can be absolute (which would start with "http://") or it can be relative to the directory containing the web page. While the WIDTH and HEIGHT attributes are mandatory, they only determine the initial space allocated to the applet. The applet can adjust these itself, as we shall see in this chapter. The double quotes around the parameter values can be omitted if the parameter value does not contain spaces or other characters that might cause confusion.

 

You can also specify parameter values to be read by your applet by placing <PARAM> tags between the <APPLET> and </APPLET> entries, one for each parameter. For example:

 

<APPLET    CODE=MyApplet.class  WIDTH=200  HEIGHT=100>

<PARAM  NAME="frameRate"  VALUE="10">

<PARAM  NAME="description"  VALUE="Some text">

 

</APPLET>

 

These tags will execute the MyApplet applet from the directory containing the HTML file, and make a parameter with the name frameRate available with the value "10", plus a second parameter, description, with the value "Some text". These values can be retrieved programmatically from within the applet – usually from within the init() method – by calling the getParameter() method with a String defining the parameter name for which the value is requested as the argument. If it is available, the parameter value is returned as a String, which you can then convert to numeric form where necessary. For example, to retrieve the value of the parameter with the name, frameRate, we could write:

 

int frameRate = 5;                         // Default frame rate

String value = getParameter("frameRate");  // Get the value of the parameter frameRate

if(value != null)

  frameRate = Integer.parseInt(value);

 

It is important to verify that the String returned by the getParameter() method is not null. It will be if there is no PARAM tag specifying the value. Note that the parameter name is not case sensitive, so "FRAMERATE" would specify the same parameter as "framerate".

 

When your applet expects to read parameter values, it is a good idea to override the default getParameterInfo() method in your applet class to identify their names, their types and their description in an array of strings. The version of the method that your applet class will inherit from the Applet class returns null. This method can be used by the applet context (the web page) to find out about your applet. For the applet MyApplet, that expects values for the parameters frameRate and description, you would implement the getParamterInfo() method as:

 

public String[][] getParameterInfo()

{

 String[][] pInfo = {

                      { "frameRate",   "integer", "The frames per second"       },

                      { "description", "String",  "Description of the animation"}

                    };

  return pInfo;

}

 

There must be three elements in each row of the array providing information about a particular parameter. The three elements in a row describe the parameter name, the type of value, and the purpose of the parameter respectively.

 

Remember to use the OBJECT and EMBED tags as shown in Chapter 1 to add Java 2 support to browsers other than appletviewer.

If you are using this book in non-linear fashion you will find more on deploying applets at the end of Chapter 12 where I also briefly discuss the security issues relating to applets. This is an extensive topic and a thorough discussion of it is beyond the scope of this book. For the most up-to-date documentation regarding the new security architecture in Java 2, refer to the web pages at: http://java.sun.com/security/

 

Let's now turn to the fundamentals of dealing with images, and then look at how we can implement an applet from the ground up – this time to handle an image.

 


Back Contents Next
©1999 Wrox Press Limited, US and UK.