What's an Applet?

So far, we've been writing stand-alone programs that can be run from the UNIX prompt. The applet is a special kind of Java object that can be run within a web browser. When you visit a plain web page, your browser send a request for the page to the server (somewhere out there on the web) and the server sends back the page, usually in a format called HTML (Hyper-Text Markup Language). HTML is just a way of specifying fonts and colors and where to place things. But sometimes embedded in the web page is a Java applet. This is a little Java object that knows how to respond to certain commands from the web browser. Usually it just displays itself and maybe responds to mouse clicks.

When you request a page with an applet on it, the server not only sends you the page of HTML, but also the applet code. (Your browser actually makes a seperate request for the applet code after receiving the HTML) Your browser, running on your local machine, then displays the page and runs the applet. The key point here is that the applet runs in the browser. Any calculations, etc., done by the applet are done locally, on your machine. We say that the applet is run on the client side.

When programming an applet, you have to understand that your code is being run on the viewer's computer, in the Java virtual machine that is inside their browser. As web content that runs within a browser, applets have many security restrictions. For example, they cannot access files on the client's machine and cannot open server sockets.

Extending  java.applet.Applet

The basic applet class is java.applet.Applet, but this class is a sort of trivial applet - it doesn't actually do anything. In order to make an applet that does something, you make your own special version of Applet, which is said to inherit from, derive from, or extend Applet. This means that your class will have all the members ( data and methods ) of Applet, plus any extra members you specify. The syntax to make a class that extends Applet is like this:

public class MyApplet extends java.applet.Applet

If you make a method in your class with the exact same signature (return type and argument types) as one in Applet, your method will be used instead of the basic one that comes with Applet. (It overides or hides the basic Applet method) This is important, since the way an applet is run is that the browser calls these basic methods.

We'll talk more about inheritance (classes extending other classes) later.

Some basic HTML

To actually use an applet, you'll have to know a small bit of HTML to make a page with an applet embedded in it. Don't worry, HTML is easy. It doesn't have variables or loops or any such things. It just has tags that are used to alter text, making it bold, or putting it in paragraphs, and other tags to insert things like tables, images and Applets. HTML tags are surrounded by less than and greater than signs like <b>, which is the tag to start bold-ness. All text after that and before the closing bold tag, </b>, will be in bold print. Most HTML tags come in pairs like this, with the closing tag being the same as the opening, but with a slash right after the less than sign. A simple HTML file might look like this:

<head><title>This goes on top of the browser</title></head> 
<body bgcolor=#ffffff link=#000099 vlink=#009999 alink=#990000 text=#000000>
<p>This is a paragraph.    Extra   spaces and single newlines
in here mean nothing.  The browser will format the paragraph for you.
<b>This sentence is in bold.</b>
<em>This sentence is emphasized.</em> (usually means italics)

Click here to see what that does. Here you see special extra tags which are used for basic structure. The html tag is used to specify that you're in the html code. The head tag is used for the header, which you'll probably just use to make a title with the title tag. A title is what is printed in the top of the browser window, after the name of the browser (Netscape or Internet Explorer, usually). Aside from the header, the other part of the file is the body. Between the open and close body tags is what is seen inside the browser. Inside the opening body tag, you can specify the colors for your page. Colors are specified as a six digit hexadecimal number preceded by a # sign. The first two digits, ranging from 00 to ff, specify how much red, the next two, how much green, the last two, how much blue. So #ffffff is white, #000000 is black and #00ff00 is bright green. The colors in the body tag are:

  bgcolorthe color of the background
textthe color of the text
linkthe color of a link to an unvisited location
vlinkthe color of a link to a previously visited location
alinkthe color of a link as you click it (an "active" link)

Paragraphs are specified with the p tag, like in the sample above. Note that single newlines and extra spaces are ignored as the browser formats your paragraphs for you. Some of the basic tags to modify text are the b and em tags shown above, to make text bold or emphasized. <center> and </center> mark regions of text that will be centered horizontally. One particularly important tag is the tag used to make links to other web locations. This is the a tag, which, when given with an href, takes the user to the specified location when pressed. It looks like this:

<a href="">This text
will be made into a link.  It will be underlined and given the color specified
by link or vlink in the body tag.</a>

The special tag we'll care most about here is the applet tag, which tells the browser to embed the specified applet at this point in the document. You'll want to give three pieces of information in the applet tag. code tells what the name of your applet class is and height and width give the size of the applet. Put the compiled java class for your applet in the same directory as the html file that refers to it. The applet tag looks like this:

<applet code=MyApplet width=300 height=300></applet>

For now we won't put anything between the opening and closing applet tags, but you can use this space to pass extra information (parameters) to the applet. Note that in specifying the extra info in the tags, like code, width and height above, you cannot put any spaces between the name of the thing, the equal sign, and the value. They must be all mushed together like above.

For more thorough HTML information, check this out. Also, you can always see the HTML source for the page you are viewing in a browser by selecting the appropriate option in the top menus. (View - Page Source in netscape). This way you can look at the HTML code, side-by-side with the output it produces in a browser. All of these pages for our class are in HTML, except for the sample Java applets, which are in Java, of course.

The Basic Applet Methods

public void paint( Graphics g )
This method tells the Applet how to draw itself. If your applet just makes a little drawing that never changes, the only Applet method you need to override is paint( Graphics g ). Note that it takes a single argument, which is a graphics object which the drawing is done with. You can name it anything, but g is the usual. Paint is always called when the applet is first loaded. Time consuming operations cannot be done in paint, but must be in a seperate thread. (more on this later)
public void init()
called when the browser first loads the applet. You use this if there is anything you need to do only once, at the beginning, such as initializing data structures.
public void update( Graphics g )
called when the applet is told to redraw itself. (When the applet is first loaded, paint is called directly. After that, update is called) If you don't provide an update method, the default Applet one is used, which just clears the applet (fills the whole thing with the background color) and then calls paint. You can set the background color with setBackground(Color).
public String getParameter( String name )
get the value of the parameter passed to the applet with the given name. See "Passing Parameters" below.

A Sample Applet

Here's a sample applet that just draws a red x across itself, so you can see how it works:

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

public class SampleApplet extends Applet
    private int w,h;

    public void init() 
        w = getSize().width;
        h = getSize().height;

    public void paint(Graphics g)

And put this in an html file:

<applet code=SampleApplet width=300 height=400></applet>

Passing Parameters

You can pass parameters from your HTML file into the applet, so that the same applet can take different manifestations depending on how it is loaded. This is done by placing param tags in between the opening and closing applet tags, which looks like this:

<applet code="Whatever" width=350 height=350>
<param name="numWidgets" value="6">
<param name="text" value="hurray!">

Ok, so how do you get the parameters from within the applet? Applets have a method called getParameter, that takes the name of the parameter and returns the value. Note that this is always a String, so if you want to pass in a number, you'll have to use Integer.parseInt(), or Double.parseDouble(), etc. on this value. To see how it is done in the above applet, check the code for that applet

Dynamic Applets

What I've shown you so far only allows you to draw simple, static applets. In order to make applets that responds to user input or that are animated, you need further techniques. Responding to user input can be done in a number of ways, mostly all involving events and listeners. Animation needs to be done with threads. Events and threads will be covered soon.