Click here to Skip to main content
12,359,751 members (70,511 online)
Click here to Skip to main content
Add your own
alternative version


17 bookmarked

How to Write Applet Code

, 19 Mar 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
An article to help write applet code.



An applet is a Java program that runs on a web page. An applet is not a stand-alone application, and it does not have a main() routine. In fact, an applet is an object rather than a class. In the Java language, a class represents a data type. Every class defines a new data type. For example, you can define a class named Point to represent a data point in the two dimensional X and Y graphing system. This class can define fields (each of type double) to hold the X and Y coordinates of a point and methods to manipulate and operate on the point. The Point class is a new data type. When discussing data types, it is important to distinguish between the data type itself and the values the data type represents. char is a data type: it represents Unicode characters. But, a char value represents a single, specific character. A class is a data type; a class value is called an object. But, when compiling applet code using the javac.exe compiler that ships with Sun’s J2EE SDK that contains the JDK, a class file is generated. That file, which has the same name as the class defined in the source code, is referred to within the applet tags that reside in the body of an HTML document. For instance, if your applet is named, then after using the javac.exe compiler, you will have a myApplet.class file. This file must be contained in quotes when embedded in the applet tags. An important point to remember is that the Swing API and the Java 2D API use a ‘J’ prefix before any component: JApplet, JFrame, JPanel, etc. To keep things simple, some applet code in this article will use the old Applet class defined in the java.awt package.

Everything that appears on a computer screen has to be written there. Many programming languages use standard output functions like printf (print format), Console.WriteLine, System.out.println, and so on. These are functions and methods that ensure that anything that appears in an output device (screen, printer) is formatted to be human-readable. The system function, however, writes to the screen. The screen of a computer is a grid of little squares called pixels. The color of each pixel can be set individually, and drawing on the screen just means setting the colors of individual pixels. A graphics context draws in a rectangle made up of pixels. A position in the rectangle is specified by a pair of integer coordinates, (x, y). The upper left corner has coordinates (0, 0). The x coordinate increases from left to right, and the y coordinate increases from top to bottom.


To write an applet that draws something, you need to know what subroutines are available for drawing. In Java, the built-in drawing subroutines are found in objects of the class Graphics, one of the classes of the java.awt package. In an applet's paint() routine, you can use the Graphics object g for drawing. This object is provided as a parameter to the paint() routine when the system calls the paint() method. Amongst others, three of the Graphics object's subroutines are:

  • g.setColor(c) is called to set the color that is used in drawing. The parameter c is an object belonging to the Color class: "g.setColor(Color.RED)”.
  • g.drawRect(x, y, w, h) draws the outline of a rectangle. The parameters x, y, w, h must be integer-valued expressions. This subroutine draws an outline of a rectangle whose top left corner is x pixels from the left edge of the applet. The width of the rectangle is w pixels, and the height is h pixels.
  • g.fillRect(x, y, w, h) is similar to drawRect except that it fills the inside of the rectangle instead of just drawing an outline.

Assume we want to write an applet that draws a checkerboard. Assume that the size of the applet is 160 by 160 pixels. Each square in the checkerboard is 20 pixels by 20 pixels. The checkerboard contains 8 rows and 8 columns. The squares are Red and Black. If the row and column number are either even or odd, then the color is Red. Otherwise, it is Black. Each square is a rectangle with a height and width of 20 pixels, so it can be drawn with the command g.fillRect(x, y, 20, 20), where x and y are the coordinates of the top-left corner of the square. Here is the tricky part. We cannot just draw a rectangle with the said dimensions and fill it with one color. So, before drawing the square, we have to determine whether it should be Red or Black. That is, we have to the correct the color with g.setColor. The coordinates at the upper-left hand corner are (0, 0). Since each square is 20 pixels high, the top of the second row is y=20. Visualize that height is the vertical Y axis on a graph. The third row is 40 pixels, followed by 60, 80, 100, 120, and 140. If we had assumed that the rows are numbered 0, 1, 2, 3, ..7, then the tops are given by y = row*20, where the row is the row number. Similarly, the left edge of the square in column col is given by col*20 (when the columns are numbered 0, 1, 2, 3.. 7). With 8 rows and 8 columns and using numbers 0, 1, 2, 3, 4, 5, 7 to represent those rows and columns, it is safe to use the for loop, a control structure that steps every element: "for (row = 0; row < 8; row++)". Similarly, 0 -7 means 8 columns: "for (col = 0; col < 8; col++)".

Now, we have to determine whether the square in the row is Red. Recall that a square is Red if both the row and column are even or odd. In Java, the modulo operator % is the most convenient to determine odd or even numbers. That is, integer N is even if N%2 is 0, and the test could be expressed as:

if ((row%2 == 0 && col%2 == 0) || (row%2 == 1 && col%2 == 1))

The && operator is a logical AND and the || operator is a logical OR. The logical OR operator (||) returns the boolean value true if either or both operands is true, and returns false otherwise. So, the above is essentially the same as asking whether row%2 and col%2 have the same value. This test can then be put more simply as:

"if (row%2 == col%2)"

The complete code:

import java.awt.*;
import java.applet.*;
public class Checkerboard extends Applet {
   public void paint(Graphics g) {
      int row;   // Row number, from 0 to 7
      int col;   // Column number, from 0 to 7
      int x,y;   // Top-left corner of square
      for ( row = 0;  row < 8;  row++ ) {
         for ( col = 0;  col < 8;  col++) {
            x = col * 20;
            y = row * 20;
            if ( (row % 2) == (col % 2) )
            g.fillRect(x, y, 20, 20);



Underlying Concepts

The above applet involved drawing a rectangle in which the squares would have a color based on the condition that if the row and column square were both odd or even, then the color would be Red. If not, the color would be Black. To fill the rectangle with squares, a for loop iterates over 8 elements to form 8 rows, and 8 elements to form 8 columns. The if statement, as we know, executes a block of code if a condition has a boolean true. If not (else), the opposite type code is executed. So, the understanding applet code not only involves color, graphics, and coordinates, but also controls flow structures and subroutines. Consider this applet:


The applet first fills its rectangle area with Cyan. Then, it changes the drawing color to Black, and draws a sequence of rectangles, where each rectangle is nested inside the previous rectangle. These rectangles can be drawn with a while loop. The while statement repeats a group of Java statements many times. It will repeat this group of statements while a condition is a boolean true.

public void paintComponent(Graphics g) {
	int count = 0;
	while (count < 50) {
		g.drawLine(20, count*5, 80, count*5);
		count = count + 1;
	g.drawString("Loop is finished.  count="+count, 10, 300);

This repeats the drawLine() call 50 times. The first time the while condition is tested, it is found to have a boolean true value because the value of count is 0, which is less than 50. Each time through the loop, the rectangle gets smaller, and it moves down and over a bit. We’ll need variables to record how the top-left corner of the rectangle is inset from the edges of the applet. The while loop ends when the rectangle shrinks to nothing. In general outline, the algorithm for drawing this applet is:

  • Set the drawing color to Cyan.
  • Fill in the entire applet (using the g.fillRect subroutine).
  • Set the drawing color to Black.
  • Set the top-left corner inset to 0.
  • Set the rectangle width and height to be as big as the applet.

While the width and the height are greater than 0:

  1. Draw a rectangle (using the g.drawRect subroutine).
  2. Increase the inset.
  3. Decrease the width and height.

Here is the applet code put together:

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

public class Rectangle extends Applet {
   public void paint(Graphics g) {

         // Draw a set of nested black rectangles on a red background.
         // Each nested rectangle is separated by 15 pixels on
         // all sides from the rectangle that encloses it.
      int inset;    // Gap between borders of applet 
                    //        and one of the rectangles.
      int rectWidth, rectHeight;   // The size of one of the rectangles.
      g.fillRect(0,0,300,160);  // Fill the entire applet with red.
      g.setColor(;  // Draw the rectangles in black.
      inset = 0;
      rectWidth = 299;    // Set size of first rect to size of applet.
      rectHeight = 159;
      while (rectWidth >= 0 && rectHeight >= 0) {
         g.drawRect(inset, inset, rectWidth, rectHeight);
         inset += 15;       // Rects are 15 pixels apart.
         rectWidth -= 30;   // Width decreases by 15 pixels 
                            //             on left and 15 on right.
         rectHeight -= 30;  // Height decreases by 15 pixels 
                            //             on top and 15 on bottom.
   }  // end paint()


Suggested Reading

  • Material written by Fred Schwarts.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Other Pref. Trust
United States United States
I started electronics training at age 33. I began studying microprocessor technology in an RF communications oriented program. I am 43 years old now. I have studied C code, opcode (mainly x86 and AT+T) for around 3 years in order to learn how to recognize viral code and the use of procedural languages. I am currently learning C# and the other virtual runtime system languages. I guess I started with the egg rather than the chicken. My past work would indicate that my primary strength is in applied mathematics.

You may also be interested in...

Comments and Discussions

-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160621.1 | Last Updated 19 Mar 2009
Article Copyright 2009 by logicchild
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid