In this lecture you will learn about Java Applets. An applet is a java program, that runs inside your web browser. Applets are the most popular use of the Java programming language. Java applets can provide animation in otherwise passive web pages, and let the user interact with the images too. GIF animation won't let you interact with the image being displayed. Furthermore, with Java and applets it is now easy to add sound to your web pages.

The nice thing about applets is that they run on the client side. The browser downloads the applet to your local machine and runs it there. The speed with which an applet is run, is relatively high, as it will be running in your browser.

An applet exists as compiled bytecode (mostly) on some computer connected to a network anywhere in the world. As soon as your browser downloads the applet, the browser's Java interpreter interprets the bytecode and executes the bytecode instructions.

Bytecodes are the compiled source code of a Java program and they can't run on any machine directly, but have to be further verified and intrepreted by each computer.

As a simple illustration, taken from Latha Ramasamy's Project

Server side:

        java code (*.java) -->|Compiler|--> Compiled Bytecodes (*.class file)

The Bytecodes travels across the network to the client:

Client side:

Bytecodes-->|Verifier|-->Verified code-->|Intrepreter|->Run applet

Applet Code

Let's take a look at the HelloWorld applet from the last lecture and try to understand what each line means: HelloWorld explained.

Calling an Applet

To be able to see a Java Applet in action, you need to embed it in an HTML file. Once we have an HTML file we can see the applet in two ways:

  • type "appletviewer example.html" from the command line

  • run a Java enabled browser, like Netscape, and load the HTML file, that is, open it's URL or file name.
  • The code that you need to put in your HTML file is pretty short, and the syntax is as follows:

    	<APPLET> 
    		[CODEBASE = applet-url]
    		CODE = applet-filename
    		WIDTH = pixel-width
    		HEIGHT = pixel-height
    		[ALT = alternate-text]
    		[NAME = applet-name]
    		[ALIGN = alignment]
    		[VSPACE = vertical-pixel-space]
    		[HSPACE = horizontal-pixel-space]
    	>
    	[<PARAM NAME=parameter VALUE=value>]
    	[<PARAM NAME=parameter VALUE=value>]
    	....
    
    	[alternate-html]
    	</APPLET>
    
    The following is an example of an HTML fragment that displays a text string:
    	<APPLET codebase="./textdir" code="MyTextApplet.class" width=300 height=200>
    	<PARAM name=message      value="Electronic Documents Course">
    	<PARAM name=font         value=Courier>
    	<PARAM name=point size   value=25>
    	</APPLET>
    
    The browser will find the applet with name "MyTextApplet", download it, and run it in the browser. It will show it in a 300 by 200 window and display the string "Electronic Documents Course" in a Courier font of point size 25.

    Parameters are very handy, because they allow you to change the appearance of the applet without having to change and recompile the Java code, e.g. you can easily change the string that the MyTextApplet is displaying by changing the message parameter.

    Applet Methods

    Following are the most important methods in the Applet class. They should provide you with enough to let you write the skeleton of your first Java applet:
  • init() - called once at applet load time
  • paint(Graphics g) - called every time the applet needs to be refreshed
  • start() - called when an applet is visited
  • stop() - called when an applet is no longer visible
  • destroy() - called when the applet is no longer alive
  • resize(int width, int height) - changes applet's viewable area
  • size() - returns an object Dimension (width and height)
  • repaint() - schedules an update()
  • update(Graphics g) - sets background color to default, paints a filled rectangle of width and height, sets the foreground color to default, and calls paint()
  • getParameter(String name) - reads a parameter from the HTML file
  • getDocumentBase() - returns the document base as specified in the attribute codebase in the HTML file
  • Reading Applet Parameters

    To read a parameter, specified with the <PARAM> tag in the HTML file, you use the getParameter() method. The following code fragment reads the parameter with name point size from the above example (MyTextApplet):
    	int point_size;
    	public void init() {
    		String ps;
    		ps = getParameter("point size");
    		if (ps == null) {
    			point_size = 12;
    		}
    		else {
    			point_size = Integer.parseInt(ps);
    		}
    	}
    
    The method init() is the method that gets called first for an applet, so you do your initializations here. This includes reading of parameter tags. The getParameter() method gets the value of the point size and stores it in ps. Then ps is checked if it is null. This is done in case there is no parameter called "point size" (remember parameters are optional). If ps is null then the point size is set to a default value (here 12), else the String is "parsed" to get an Integer value.

    Doing Graphics

    The Graphics object is used for drawing in applets. The Graphics class is probably the most important class in the java.awt package.

    The java.awt package provides an integrated set of classes to manage user interface components such as windows, dialog boxes, buttons, checkboxes, lists, menus, scrollbars, and text fields (AWT stands for Abstract Window Toolkit). The package's classes can be divided into three groups:

  • Graphics- these classes define colors, fonts, images, polygons, etc.

  • Components- these classes are GUI components such as buttons, menus, lists, etc.

  • Layout Managers- these classes control the layout of components within their container.
  • We will learn how the GUI components work in lecture 3. The Graphics class contains methods for basic drawing like drawLine, fillRect, drawString, and also methods for image retrieval and display. The graphics context is owned by the browser and passed to the applet in the paint() method.

    Lets extend out HelloWorld example and draw an oval around the text: draw ovals around text.

    Images

    The java.awt.image package that provides classes for managing image data, including color models, cropping, color filtering, setting pixel values, and grabbing snapshots. The Image class itself is part of thejava.awt package though.

    Java supports GIF and JPEG image formats. The following code fragment reads in an image called "imagename.gif" and draws the image at location (x,y) on the screen:

    	Image img;
    	public void init() {
    		img = getImage(getDocumentBase(), "imagename.gif");
    	}
    	public void paint(Graphics g) {
    		g.drawImage(img, x, y, this);
    	}
    
    The call to getImage, an Applet method, automatically creates an image. Thus, you need to import the java.awt.Image class.

    Double Buffering and Clipping

    To create smoother graphics you can use two techniques: double buffering and clipping.

    Double buffering is the technique of doing all your drawing into an offscreen buffer, and then copying the contents of the buffer to the screen all at once. This prevents flickering that would otherwise result from erasing and redrawing the figure. The buffer is an offscreen Image created with the createImage method from the java.awt package. To draw an image offscreen, you simply use its Graphics object, which is obtained with the getGraphics method of the java.awt.Graphics class. Once the drawing is complete in the offscreen image, the applet can draw it in its screen.

    Compare the next two applets that just display an image (notice the flickering in the first applet): Without Double Buffering and With Double Buffering.

    Clipping is the second important technique for smoother graphics. It often happens that only a small region of a larger area has to be erased and redrawn. However, the paint method only knows how to redraw the entire applet window, not small regions of it. We can set a small rectangular clipping region in the Graphics object we use. This would tell the system that it only needs to draw within the specified rectangle and that it can ignore any drawing outside of this rectangle. When we know the area of an applet that needs to be redrawn, we can specify a clip rectangle that surrounds the area and do a full redraw, knowing that the applet will only redraw the portion inside the clipping rectangle. This method of drawing leads to much faster and less flickering redrawing.

    	g.clipRect(r.x, r.y, r.width, r.height);
    	g.drawImage(background, 0, 0, this);
    

    Animation

    All applets we have seen so far were passive, they responded to methods called by the system, but take no action of their own. Animation is active, we need to draw something over and over again. We cannot use the init(), paint(), or any of the other standard applet methods to do this. These methods are supposed to do a simple job and then return to the system. To perform our animation we need to create a Thread object to create a separate thread of execution. A thread, defined in the java.lang package (which Java automatically imports), defines a set of instructions the browser can execute at the same time it runs the applet. By using one or more threads, a Java applet can perform two or more operations at the same time (multithreaded).

    As we have seen, within a Java applet you may find an init and a start function. Java calls the init function first and when init is done, Java calls start. When the applet uses Thread objects, the applet must call the Thread object's start function, which in turn will call the Thread object's run function. Unlike Java applets, Thread objects do not have an init function that executes first.

    The applet's start method creates this animation thread and starts it by calling the thread's start() method. The stop() method stops the thread by calling stop() on it. The thread is created by passing the Applet object (i.e. this) to the thread constructor. This creates a thread that, when started, executes code in the run() method of the applet. The run() method is the method that performs the actual animation. For example, it draws an image, goes to sleep for a while by calling Thread.sleep(), and then loops to draw the next image. To create a thread which runs the applet's run function, the applet must support the Runnable interface. When you use the Runnable interface for a class, you tell Java that the class contains a run() function:

    	public class HelloAnim extends Applet implements Runnable {
    

    Let's try to animate our HelloWorld example: HelloWorld animated.

    The next applet is an example of animation with images: Image animation.

    Trackers and Animation

    This image animation works resonably well. There are some problems however:

  • it starts the animation before the images are all loaded, and

  • it has no provisions for handling errors while loading images.
  • The way to solve these problems is to use a MediaTracker object, which is part of the java.awt package. The MediaTracker class is a utility class to trace the status of a number of media objects. Media objects could include images as well as audio clips (currently only images are supported). This class lets you register images and then call a method that blocks until they have completed loading. It also allows you to check for errors in the loading process. The drawback is that sometimes there is a significant wait.

    Let's remove the flickering from our image animation example: ImageTracker.

    Java Packages

    For a full blown explanation of all the packages that Java supplies goto: http://java.sun.com/products/JDK/CurrentRelease/api/packages.html.

    For example, you want to draw a line, but are not sure what parameters it takes. Then go to this site, follow the java.awt package link, since drawLine is part of the java.awt.Graphics class. Once there follow the 1.20 Graphics Class link, and you will find the drawLine routine in there, and you will see that it takes four parameters. If you are still in doubt and want to know what the parameters mean, then follow the link off the drawLine method, which is labeled §1.20.16 for detailed explanation of what the parameters mean.

    Lab2

    Let's try to implement and run some applets: Lab 2.


    Java Home
    Lectures
    Labs