A Simple Applet


The DemoApplet Applet:

This is a simple applet, called DemoApplet. It loads and displays three images and a rectangle on a red background, one image twice. If the images cannot be loaded, it instead displays Error loading images.

Sorry, your web browser does not support Java.

Copies of the files are available here: To save these files, right-click on the link and choose "Save As...", "Save Target As...", "Save Link As...", or whatever your web browser says. If you just click on the link, your web browser will probably load the file instead of saving it.

The AppletDemoPage.html Web Page:

The contents of AppletDemoPage.html are:

		<title>Applet Image Demo</title>

		<h1>Applet Image Demo</h1>
			alt="You need to enable Java">
			Sorry, your web browser does not support Java.

Web pages are written in a formatting language called HTML. A formatting language is sort of like a programming language, except that instead of specifying a program, a formatting language specifies how something should be displayed.

HTML is composed of text and formatting indicators, called tags. Most tags come in pairs, called the opening tag and the closing tag, and affect the formatting between them. Some tags have an immediate effect, and do not need to be closed.

An HTML tag is usually a string, called the name, enclosed in < and > brackets. If there is a closing tag, it will be the same except for having a / just after the < and before the name. Some tags also have parameters after the name but before the >.

What follows is an incomplete listing of HTML tags. For more information see http://www.w3schools.com/

General HTML Tags:

<html> and </html> indicate that everything between them is written in HTML.

<head> and </head> indicate that everything between them is the header.

<title> and </title> specify the title that appears at the top of the web browser.

<body> and </body> indicate the part of the file to be displayed in a web browser.

Text Formatting HTML Tags:

<h1> and </h1> specify that the text between them is to be displayed as a large heading. The exact appearance will vary between web browsers. <h2>, <h3>, <h4>, <h5>, and <h6> also exist, with <h1> being the largest and <h6> being the smallest.

<b> and </b> specify that the text between them is to be bold.

<i> and </i> specify that the text between them is to be in italics.

<br> specifies a line break. If you do not put these in, the web browser will break your lines at the edge of the window. HTML treats any combination of line breaks, tabs, and spaces in the .html file as a single space.

Other HTML Tags:

<a> and </a> specify a hyperlink. It needs one parameter: href="http://www.some-web-site.com/". The quotes are needed. The text between the <a> and </a> tags appears as the link, and clicking on it sends you to http://www.some-web-site.com/

<applet> and </applet> specify an applet. Strictly speaking, it only needs three parameters, but it is a good idea to put in five. They are: Text that appears between the <applet> and </applet> tags is displayed if the user's web browser does not even know what an applet is.

Making the Applet Work:

The source file is DemoApplet.java and is in a directory named examples. This directory also contains the grass.gif, dirt.gif, and stone.gif images. It is a good idea to put your images in the same directory as your source code, because then it is easy to refer to them in your program and there is no way they will be left out of the jar file when you build it.

The web page and .jar file are in the directory above examples, which we will call Top-Directory.

To compile DemoApplet.java and produce a .jar file from Top directory on Unix (Hercules), you enter

javac examples/*.java
jar cf ImageDemo.jar examples

In order to run DemoApplet, we need open it in a web browser. I am not going into this here because it is already on the other web page.

The DemoApplet.java File:

The First Bit of the File:

//  DemoApplet.java

package examples;

import java.applet.*;
import java.awt.*;

The first three lines are a comment saying this is the file called DemoApplet.java. They are ignord by the compiler.

package examples; indicates that AppletDemo.java is part of the package named examples. A package is a group of Java classes (program bits) that the Java compiler thinks of as going together. Every Java file is in exactly one package, and that package must have the same name as the directory the file is in. If you do not specify a package, your file will be in the default package. This is a bad thing and should be avoided.

The lines that begin with import tell the compiler to go and get us classes from other packages so that we can use them in our program. Specifically,import java.applet.*; tells the compiler to get * (computer-speak for "everything") from the java.applet package, and import java.awt.*; tells the compiler to get * from the java.awt package. The main thing we want from java.awt is the Image class, but we will need some other things as well.

The Start of the DemoApplet Class:

public class DemoApplet extends Applet

The first of these lines says we are creating a class named DemoApplet. This class is public, which means that in can be used by anyone. As a web browser is not even part of the same program, anything other than public will mean that the applet cannot be run. extends Applet means that this class will be a lot like Applet (which we got from the java.applet package), but we are going to change a few things. The remainder of the class specifies these changes.

The { indicates that everything until the matching } will be part of the DemoApplet class. So as not to keep you in suspense, the } is at the end of the file.

As an important note, Java allows you to specify as many classes as you want in one file. However, each public class must be specified in a file with the same name as the class, so you can't put more than one in a file. You can also specify classes that are not public, by simply leaving out the keyword public. Such a class can only be used within its own package.

The Variable Declarations:

	private Image grass;
	private Image dirt;
	private Image stone;

Here we declare three variables of type Image (which we got from the java.awt package).

We have specified these variables as private, which means that they cannot be used by anyone outside of this class. There is a good reason why we did this: Otherwise, somemone might change those values to be something we didn't expected them to be, and then the program might crash. So, to be on the same side, we always make our variables private unless we have a really good reason not to.

The init Function:

	public void init ()

This is the declaration for a function called init, in which we set up our applet. It takes no parameters, and returns void, which is to say, nothing. This function is also declared to be public, and as we can recall, that means that it can be used by anyone. We need it to be public because the web browser is going to call it when the applet has been loaded into the web page.

The loadImages Function:

	private void loadImages()
		MediaTracker tracker = new MediaTracker(this);
		grass = getImage(this.getClass().getResource("grass.gif"));
		tracker.addImage(grass, 0);
		dirt = getImage(this.getClass().getResource("dirt.gif"));
		tracker.addImage(dirt, 1);
		stone = getImage(this.getClass().getResource("stone.gif"));
		tracker.addImage(stone, 2);

		try { tracker.waitForAll(); }
		catch (InterruptedException e) {}

You do not need to understand this function.

All you need to know is that it loads the images in the files "grass.gif", "dirt.gif", and "stone.gif" into the variables named grass, dirt, and stone. These variables are of the Image type and thus can be used to store images.

As this function is quite useful, you may want to copy it into your own applets. It should not be too hard to modify it to load differant images instead.

The paint Function:

	public void paint (Graphics g)
		g.fillRect(0, 0, 1000, 1000);
		g.setColor(newColor(238, 221, 204));
		g.fillRect(120, 80, 100, 60);
		g.drawImage(grass, 40, 40, this);
		g.drawImage(dirt, 48, 60, this);
		g.drawImage(stone, 100, 32, this);
		g.drawImage(stone, 124, 32, this);

This is another function, like init, that will be called by the web browser. However, the paint function is used to display the applet, and so it will be called whenever the applet is displayed. Like init, paint has to be public so that the web browser can call it.

There is a very important thing to remember here: You do not know when paint will be called. It will definitely be called when the web page is loaded (and after init), but after that it is entirely unpredictable. The ONLY thing you know is that it will never be called while it is currently running. Because of the uncertainty about when it will be called, you should only put display operations in the paint function. It is a bad idea to change the state of the program in any way, such as changing the values of non-local variables.

The init finction takes a Graphics as a parameter. Graphics is a class we got from the java.awt package (like Image) that allows us to display images, shapes, text, etc. visually. You cannot make your own Graphics; you can only use ones that you get from somewhere else. This may be because the a Graphics has to deal with hardware, and thus would be very hard to set up correctly.

Any command to our Graphics (called "g") will contain "g." before the function name, where "g" is the name of the Graphics. Here, the "." indicates the the function is part of the Graphics class, and does not mean that we have a number with a decimal point.

Changing the Drawing Colour:

g.setColor(Color.RED) calls a function called setColor in g. As a parameter, it takes a Color (also from the java.awt package).

The Color can be:

Drawing Geometic Shapes:

g.fillRect(0, 0, 1000, 1000) calls a function called fillRect in g. It takes four integer parameters, representing the x and y coordinates of the top-left corner, the width, and the height, and draws a solid rectangle of those dimensions in the colour set with g.setColor.

Here, we draw a really big rectangle (1000 by 1000 pixels) becuase it is easier than working out the size of our applet. If we checked, we specified in our HTML file that our applet was 320 pixels wide and 240 pixels high. The portion of the rectangle that is outside the bounds of our applet will not be displayed. Although an applet can be specified to be any size, keep in mind that modern computer screens are normally somewhere between 1024 by 768 pixels and 1920 pixels by 1200 pixels.

The g.fillRect(120, 80, 100, 60); line draws a second rectangle on top of the first. This rectangle has its top-left corner at position x = 120, y = 80, and is 100 pixels wide and 60 pixels high. It is drawn in the same colour as the background for the web page.

If we had wanted to draw a hollow rectangle (just a line around the outside) we would have used the g.drawRect function instead. There is, however, an annoying inconsistancy between the draw functions and the fill functions: The fill functions draw a rectangle that at 32 pixels across (for example), while the draw functions draw a rectangle where the right line is 32 pixels from the left line. This means a rectangles (or anything else) drawn with the drawRect function will be one pixel wider than a rectangle drawn with the fillRect function. YOU HAVE BEEN WARNED!

As an important note, the top-left corner of you applet is position x = 0, y = 0. A positive change in x is to the right, and a positive change in y is down. The Y axis is the opposite of mathematics, so be careful. All distances are measured in pixels.

The common functions like fillRect are:

Drawing Images:

g.drawImage(grass, 40, 40, this) calls a function named drawImage in g. It takes four integer parameters, representing the image to draw, the x and y coordinates to draw its top-left corner at, and an ImageObserver. You do not need to know what an ImageObserver is, only that your applet counts. Thus, we can use this for the fourth parameter. The image is not affected by the colour we set with g.setColor.

The End of the DemoApplet Class:


This is the matching } to go with the { at the start of the class. It shows the compiler that this is the end of the DemoApplet class. As a result, we cannot added any more variables or functions to the class, but we can now use it elsewhere. For example, we want to use this class in our web page.

Event-Driven Applets:

Everything our applet does will have to be started from either the init method or the paint method (actually there are two more methods, called start and stop, but they won't help us). Of these, we don't know when the paint method will be called, so we shouldn't start anything with a lasting effect in it. That appears to mean that everything has to be started from init.

At first, this does not appear to be a problem; everything in a C/C++ program had to be started from main, and those programs worked fine. However, in C/C++ we have cin and getline, which cause the program to wait until the user types some input. Although Java does have an equivilent, it does not work well with applets.

Actually, this problem comes up in visual programming in any language, not just Java. And, luckily for us, there is a solution: event-driven programming.

In event-driven programming, functions are made to execute on certain conditions. For example, the init function executes on the condition the applet has loaded. The paint function executes on the condition the applet needs to be displayed. It also possible to add other conditions like the user pressed the button or 0.27 second have passed.

Java was designed with event-driven programming in mind, so there are four ways to start functions in an applet:
Between these, you can have your applet behave in almost any way you can imagine.

In our applet, we only used the first two. For an example of an applet that uses them all, click here.

The DemoApplet Applet:

Sorry, your web browser does not support Java.

Back to miscellaneous stuff page
Back to home page