Exercise 5

The aim of this exercise is to explore the differences between applications and applets

Part A - Applets

	A basic extension of the java.applet.Applet class
	@author Russell Beale (c) 1998
	@param none

import java.awt.*;

public class VerySimpleApplet extends java.applet.Applet
	public void paint(Graphics g){
	    g.drawString("Hello, Applet World!", 10, 40);
	    g.drawString("Writing is easy", 20, 60);
	    g.drawString("Coding is not too bad", 30, 80);
	    g.drawString("Ah, Java!!", 40, 100);

Here's a basic applet - copy it and save it as VerySimpleApplet.java. Compile it, and then try and run it with

java VerySimpleApplet

What happens?

You need to either embed it in a web page, or to use an applet viewer. Try both.

To run it in a web page, use the following HTML code.

<TITLE>HTML page with an applet on it</TITLE>
Here is a simple Java applet.
<APPLET CODE="VerySimpleApplet.class" WIDTH=200 HEIGHT=150>
Anything I put here is displayed by a browser that does not understand Applets

If you do not have a browser, or, more likely, it is an older version that does not support the latest features of the Java language, use the applet viewer built into the JDK, by typing

appletviewer VerySimpleApplet.html

Things to Note

  1. There is no main ! Applets are somewhat more complicated than applications, in that they have different phases of operation, e.g. initialisation, starting, painting and so on. The browser or appletviewer calls methods that relate to these as necessary. The default implementation these methods in java.applet.Applet do nothing - you overide these to make the applet perform as you want. The browser/appletviewer starts the applet for you, and so you don't require a main method.
  2. The only method we define here is paint. It is not the only method in the class - the others exist in the default Applet code, but it's only the painting that we want to alter, hence it's only this we need to override.
  3. paint() takes an argument - an instance of Graphics. This is created by the browser, so we don't have to worry about it - but check out what it is by looking at the documentation in its API. This graphics context is what we use to draw on, and defines how things will appear.
  4. Writing strings to the screen is easy, as is changing the colour. Note that the coordinates are increasing to the right for x and down for y, with (0,0) as top left, by default.
  5. Applets are a very common use of Java. They are more complicated because they exist within and interact with the browser. However, they are less powerful than a full application, becuase of their security restrictions.


  1. Using the information in the documentation, alter the fonts. Hint: Font f = new Font("TimesRoman", Font.BOLD, 36);
  2. Other basic applet methods are