CS396N - Web Programming
Lecture 3
Chapter 9 - Applets


Applet Creation:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>
<HEAD>
  <TITLE>A Template for Loading Applets</TITLE>
</HEAD>

<BODY>
<H1>A Template for Loading Applets</H1>
<P>
<APPLET CODE="AppletTemplate.class" WIDTH=120 HEIGHT=60>
  <B>Error! You must use a Java-enabled browser.</B>
</APPLET>

</BODY>
</HTML>
 

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

public class AppletTemplate extends Applet {

  // Variable declarations.

  public void init() {
    // Variable initializations, image loading, etc.
  }

  public void paint(Graphics g) {
    // Drawing operations.
  }
}
 
 

Sample Applet


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

public class JavaJump extends Applet {
  private Image jumpingJava; // Instance var declarations here

  public void init() {       // Initializations here
    setBackground(Color.white);
    setFont(new Font("SansSerif", Font.BOLD, 18));
    jumpingJava = getImage(getDocumentBase(),
                           "images/Jumping-Java.gif");
    add(new Label("Great Jumping Java!"));
    System.out.println("Yow! I'm jiving with Java.");
  }

  public void paint(Graphics g) {  // Drawing here
    g.drawImage(jumpingJava, 0, 50, this);
  }
}

Corresponding HTML Code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>
<HEAD>
  <TITLE>Jumping Java</TITLE>
</HEAD>
<BODY BGCOLOR="BLACK" TEXT="WHITE">
<H1>Jumping Java</H1>
<P>
<APPLET CODE="JavaJump.class" WIDTH=250 HEIGHT=335>
  <B>Sorry, this example requires Java.</B>
</APPLET>
</BODY>
</HTML>
 

Standard Output

System.out.println(" ... ");

JAVA Console - Netscape or IE

Appletviewer - output sent to window that started applet
 
 

Creating an Applet

  1. Using some editor, create the Java source code for an applet. Save the source code with the extension .java.
  2. Using the javac compiler compile the source code. javac will create the bytecode file, with same name but with the extension .class.
  3. Using some editor, create an HTML document ( must have extension .html or .htm) in which you use an APPLET tag and refer to the bytecode file just created.
  4. Using any Java-enabled browser, or appletviewer, open the HTML file just created.
Example

Using a text editor create the following Java source code:
import java.awt.*;
import java.applet.*;

public class First extends Applet{
    public void paint(Graphics g) {
        g.drawString("MY FIRST APPLET",5,25);
    }
}

Save the file as First.java.
The name of the file must be the same as the name of the class in the source code, with the extension .java.

Compile the source code using javac. At the DOS prompt, issue the command:
> javac First.java

javac will create the bytecode file named First.class.

Create the following HTML file:
<HTML>
<TITLE> First Java Applet </TITLE>
<H3> This is my first Java applet </H3>
<HR>
<APPLET CODE = "First.class" WIDTH=100 HEIGHT=30>
</APPLET>
<HR>
<H4>Applet is done ........ </H4>
</HTML>

Save this file with the extension.html.
 

In Netscape or IE, open the HTML file.


 

Explanation

import java.awt.*;
import java.applet.*; public class First extends java.applet.Applet public void paint(Graphics g) {
    g.drawString("MY FIRST APPLET",5,25);
}

Attributes of the HTML APPLET tag

The following table describes the attributes used with APPLET tag:

CODE - the name of .class file
    - Required attribute.
    - Syntax: CODE="filename.class"

WIDTH and HEIGHT - screen area for the applet in pixels
    -Required attributes.
    -Syntax: WIDTH=a_number HEIGHT=a_number

CODEBASE - specifies the base URL or directory
    -Syntax: CODEBASE=base_URL
     -Must use the CODEBASE attribute if the .class file is not in the current directory.

NAME - used for interapplet communication
    -Syntax: NAME=name

ALIGN - Aligns the applet as an embedded image
    -Syntax: ALIGN=left|center|right|top|texttop|middle|absmiddle|baseline|bottom

VSPACE - Forces n blank pixels above and below the applet
    -Syntax: VSPACE=n

HSPACE - Forces n blank pixels to left and right of the applet
    -Syntax: HSPACE=n
 

Reading Applet Parameters

1. The Dimension class
    - Applet size specified in the APPLET tag as values of the attributes HEIGHT and WIDTH.
    - Accessed within the applet using the Dimension class.

Example

The following applet prints the height and width of the applet rectangle, specified by the HTML tag APPLET.

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

public class Size extends Applet{
    public void paint(Graphics g){
        Dimension d = getSize();
        g.drawString("Height is = "+d.height+ " Width is
            ="+d.width,10,100);
    }
}

The HTML code for this:

<TITLE> The Size Applet </TITLE>
<H3> This applet prints the height and width of the applet rectangle.</H3>
<HR>
<APPLET CODE = "Size.class" HEIGHT=300 WIDTH=200></APPLET>
<HR>
<H3> We are done …… </H3>

2. Using PARAM HTML tag
    - HTML document send values: text string, x-position, y-position, font, a file name, etc., to an applet
    - Use PARAM tag in the HTML document
    - PARAM tag captured by the applet using the getParameter()method.
    - PARAM tag is placed within <APPLET> …</APPLET>.
    - PARAM tag requires two attributes: NAME and VALUE.
    - Syntax for PARAM tag:
        <PARAM NAME=". . . . . " VALUE=".. . . . . ">

Example
Java Code
import java.applet.Applet;
import java.awt.*;

public class HelloWWW2 extends Applet {
  public void init() {
    setFont(new Font("SansSerif", Font.BOLD, 30));
    Color background = Color.gray;
    Color foreground = Color.darkGray;
    String backgroundType = getParameter("BACKGROUND");
    if (backgroundType != null) {
      if (backgroundType.equalsIgnoreCase("LIGHT")) {
        background = Color.white;
        foreground = Color.black;
      } else if (backgroundType.equalsIgnoreCase("DARK")) {
        background = Color.black;
        foreground = Color.white;
      }
    }
    setBackground(background);
    setForeground(foreground);
  }

  public void paint(Graphics g) {
    g.drawString("Hello, World Wide Web.", 5, 35);
  }
}

HTML Code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>
<HEAD>
  <TITLE>Customizable HelloWWW Applet</TITLE>
</HEAD>
<BODY>
<H1>Customizable HelloWWW Applet</H1>
<P>
<APPLET CODE="HelloWWW2.class" WIDTH=400 HEIGHT=40>
  <PARAM NAME="BACKGROUND" VALUE="LIGHT">
  <B>Error! You must use a Java-enabled browser.</B>
</APPLET>
<P>
<APPLET CODE="HelloWWW2.class" WIDTH=400 HEIGHT=40>
  <PARAM NAME="BACKGROUND" VALUE="DARK">
  <B>Error! You must use a Java-enabled browser.</B>
</APPLET>
<P>
<APPLET CODE="HelloWWW2.class" WIDTH=400 HEIGHT=40>
  <B>Error! You must use a Java-enabled browser.</B>
</APPLET>
</BODY>


 
 

Applet Life Cycle

public void init()
    - Called when the applet is loaded
    - Method used for initialization of data

public void start()
    - start() method called to begin applet execution.
    - Called after the init() method each time the applet is revisited in a Web page.
    - Method used to perform any operation required when the this applet is loaded.
    - Implementation of this method provided by the Applet class does nothing.

public void stop()
    - stop() is called when browser or appletviewer informs applet that it should stop its execution.
    - Called when Web page that contains this applet has been replaced by another page, and t before the applet is to be destroyed.
    - Method may be used to perform any operation required each time the Web page containing it is no longer visible (e.g. suspending an animation).
    - Implementation of this method provided by the Applet class does nothing.

public void destroy()
    - destroy() called by the browser or appletviewer to inform this applet that it is being reclaimed and that it should destroy any resources that it has allocated.
    - Method to perform any operation rquired before it is destroyed (e.g. killing threads).
    - The implementation of this method provided by the Applet class does nothing.

Graphics Operations

Graphics Levels:

AWT 1.1 Graphics

Font Class

Example

import java.applet.Applet;
import java.awt.*;
public class Fonts extends Applet {
   Font font1, font2, font3, font4, font5;
   public void init(){
      font1 = new Font("Serif",Font.ITALIC,10);
      font2 = new Font("SanSerif",Font.BOLD,15);
      font3 = new Font("Monospaced",Font.PLAIN,20);
      font4 = new Font("Helvetiva",Font.BOLD+Font.ITALIC,25);
      font5 = new Font("Courier",Font.PLAIN,30);
   }

   public void paint(Graphics g){
      g.setFont(font1);
      g.drawString("Serif in Italic with size 10",30,10);
      g.setFont(font2);
      g.drawString("SanSerif in Bold with size 15",30,45);
      g.setFont(font3);
      g.drawString("Monospaced in plain with size 20",30,75);
      g.setFont(font4);
      g.drawString("Helvetica in Bold italic with size 25",30,120);
      g.setFont(font5);
      g.drawString("Courier in Plain with size 30",30,150);
   }
}

Color Class

1. Create a Color object:
    Color color_object;

2.  Initialize the Color object using new and a constructor:
    color_object = new Color (r,g,b);
    r,g and b are integers between 0 and 255 specifying color components.

3. Install the Color object, using the setColor() method of the Graphics class.
    setColor(color_object_name)

Java provides 13 predefined Color objects with static field names of the Color class:
Color.black         Color.blue      Color.cyan
Color.darkGray      Color.gray      Color.green
Color.lightGray     Color.magenta     Color.orange
Color.pink          Color.red       Color.white
Color.yellow
 

Example

import java.awt.*;
import java.applet.Applet;
public class Colors extends Applet{
   Color myColor;
public void paint(Graphics g)   {

 myColor = new Color(100,0,255);
 g.setColor(myColor);
 g.drawString("Pace University 1",10,20);
 g.setColor(Color.black);
 g.drawString("Pace University 2",10,40);
 g.setColor(Color.blue);
 g.drawString("Pace University 3",10,60);
 g.setColor(Color.green);
 g.drawString("Pace University 4",10,80);
 g.setColor(Color.magenta);
 g.drawString("Pace University 5",10,100);
 g.setColor(Color.red);
 g.drawString("Pace University 6",10,120);
 g.setColor(Color.yellow);
 g.drawString("Pace University 7",10,140);
 myColor = myColor.darker();
 g.setColor(myColor);
 g.drawString("Pace University 8",10,160);
 myColor = myColor.brighter();
 g.setColor(myColor);
 g.drawString("Pace University 9",10,180);
}
}


 

Graphics Class

Graphics class methods

drawLine(x1,y1,x2,y2)
        - x1, x2, y1, y2 - all integers.
        - Draws a line between (x1, y1) and (x2, y2)

drawRect(x,y,width,height)
        - x, y, width, height - all integers
        - Draws a rectangle with the specified width and height, at the top left corner at (x,y)

drawRoundRect(x,y,width,height,arcWidth,arcHeight)
        - x, y, width, height, arcWidth, arcHeight - integers
        - Draws an outlined round cornered rectangle
        - left and right edges of the rectangle are x and x+width, respectively.
        - top and bottom edges of the rectangle are at y and y+height.
        - ArcHeight and arcWidth determine the horizontal and vertical diameters at the four corners.
 

Example

Applet draws:
    - a line from (30,30) to (60,60)
    - a rectangle at (10,10) with width & height 100 & 100
    - a round rectangle at (20,20) with width & height 80 & 80

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

public class Graphics1 extends Applet{
 public void paint(Graphics g){
    g.setColor(Color.green);
    g.drawLine(30,30,60,60);
    g.setColor(Color.blue);
    g.drawRect(10,10,100,100);
    g.setColor(Color.red);
    g.drawRoundRect(20,20,80,80,25,25);
 }
}


 
 

fillRoundRect(x,y,width,height,arcWidth,arcHeight)
    - x, y, width, height, arcWidth, arcHeight - integers
    - Fills an outlined round cornered rectangle.
    - left and right edges of the rectangle are x and x+width, respectively.
    - top and bottom edges of the rectangle are at y and y+height.
    - arcHeight and arcWidth determine the horizontal and vertical diameters at the four corners.

fillRect(x,y,width,height)
    - Same as drawRect(), but fills rectangle with default color.
 

Example

Draws two rectangles except that the rectangles are now filled.

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

public class Graphics2 extends Applet{
    public void paint(Graphics g){
        g.setColor(Color.blue);
        g.fillRect(10,10,100,100);
        g.setColor(Color.red);
        g.fillRoundRect(20,20,80,80,25,25);
    }
}


 

drawOval(x,y,width,height)
    - x, y, width, height - all integers.
    - Draws an ellipse within the square (Square will not show).

fillOval(x,y,width,height)
    - x, y, width, height - all integers
    - Draws an ellipse and fills with the current color.
 

Example

Applet draws an ellipse at (10,10) and a filled ellipse at (20,20).

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

public class Graphics3 extends Applet{
    public void paint(Graphics g){
        g.setColor(Color.blue);
        g.drawOval(10,10,150,100);
        g.setColor(Color.red);
        g.fillOval(20,20,40,80);
    }
}


 

drawArc(x,y,width,height,startAngle,arcAngle)
    - x, y, width, height, startAngle, arcAngle - all integers
    - The center of the arc will be at the center of  a square
    - The startAngle is the angle made with the horizontal line.

fillArc(x, y, width, height, startAngle, arcAngle)
    - x, y, width, height, startAngle, arcAngle - all integers
    - The center of the arc will be at the center of a square as.
    - The startAngle is the angle made with the horizontal line.
 

Example

Applet draws a pie and a filled pie.

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

public class Graphics4 extends Applet{

    public void paint(Graphics g){
        g.setColor(Color.blue);
        g.drawArc(10,10,100,100,15,45);
        g.setColor(Color.red);
        g.fillArc(10,10,100,100,135,45);
   }
}


 

drawPolygon(xArray,yArray,n)
    - n is an integer, representing the number of points.
    - xArray and yArray are integer arrays with n elements each.
    - Draws a polygon by joining lines (x[0],y[0]) and (x[1],y[1]), (x[1],y[1]) and (x[2],y[2]), … ,
       (x[n-2],y[n-2]) and (x[n-1],y[n-1]),
 

Example

Applet draws a polygon with 8 vertices using arrays of 9 elements

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

public class Graphics9 extends Applet {

int x[] = {100,70,60,70,100,130,140,130,100};
int y[] = {10,20,50,80,90,80,50,20,10};
int n = 9;

    public void paint(Graphics g) {
        g.setColor(Color.green);
        g.drawPolygon(x,y,n);
    }
}


 

fillPolygon(xArray,yArray,n)
    - n is an integer, representing the number of points.
    - xarray and yarray are integer arrays with n elements each.
    - Draws, a filled with default color, polygon by joining lines (x[0],y[0]) and (x[1],y[1]), (x[1],y[1])
        and (x[2],y[2]), …, (x[n-2],y[n-2]) and (x[n-1],y[n-1]).
 

Example

Applet draws the same polygon  but fills it with green color.

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

public class Graphics10 extends Applet {

int x[] = {100,70,60,70,100,130,140,130,100};
int y[] = {10,20,50,80,90,80,50,20,10};
int n = 9;

    public void paint(Graphics g) {
        g.setColor(Color.green);
        g.fillPolygon(x,y,n);
    }
}


 
 

Drawing Images

Example

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

// An applet that loads an image from a relative URL.

public class JavaMan1 extends Applet {
  private Image javaMan;

  public void init() {
    javaMan = getImage(getCodeBase(),"images/Java-Man.gif");
  }

  public void paint(Graphics g) {
    g.drawImage(javaMan, 0, 0, this);
  }
}
 

Comments:

getImage(getCodeBase(),"images/Java-Man.gif")
    getImage(codebase, relative_path);
    public URL getCodeBase() - returns path of the Java code
    public URL getDocumentBase()- returns path of the HTML Doc

g.drawImage(javaMan, 0, 0, this)
    drawImage(Image image,int left,int top,ImageObserver observer);
                                                ^ current window

Example
// An applet that loads an image from a Absolute URL.
import java.applet.Applet;
import java.awt.*;
import java.net.*; // Required for web access

public class JavaMan2 extends Applet {
  private Image javaMan;

  public void init() {
    try {
      URL imageFile = new URL("http://www.corewebprogramming.com" +
                              "/images/Java-Man.gif");
      javaMan = getImage(imageFile);
    } catch(MalformedURLException mue) {
      showStatus("Bogus image URL.");
      System.out.println("Bogus URL");
    }
  }

  public void paint(Graphics g) {
    g.drawImage(javaMan, 0, 0, this);
  }
}