Applets

The hierarchy

   Object -> Component -> Container -> Panel -> Applet ->  your program
                              \
                                 -->  Window -> Frame : for applications
Note: Applets can open windows and frames also.

Words Applet

Here we display words at random on the screen.
Suppose the file name is Words.java.
 import java.applet.*;
 import java.awt.*;

public class Words extends Applet 
 {
   int random(int i)
 {
   return Math.round(Math.random()*i) ;  // calls to class methods
 }

   public void paint(Graphics g)       // overriding paint
 {
   String fontName = getParameter("font");  // taking parameters from html file
   Font f = new Font(fontName, Font.BOLD,18)
   g.setFont(f);
   for (int i = 0; i<10; i++)
      g.drawString(random(200),random(100),"Don't touch"); // graphics upside down
 }  
}

Corresponding html file

 < HTML >
    < HEAD >
    < TITLE > Whatever < /TITLE >
    < /HEAD >
    < BODY >
    < APPLET CODE="Words.class" WIDTH=283 HEIGHT=190 >
    < PARAM NAME=font VALUE="Helvetica" > 
    < /APPLET >
    < /BODY >
< /HTML >

Applet Syntax

Applet Methods

Applets are event-driven. The most basic event is visiting the html page on which the applet resides. We will discuss other events later.

Graphic Methods inherited from Component

Graphics objects are measured in pixels.

Another Applet Example

/*
   Simple fractal program that illustrates recursion.
   Recall that the vector <-y,x> is perpendicular to the vector .
   Check the dot product.
 */

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

public class Fractal extends Applet {

	public void init()
	{
           resize(600,400);
	}	
	
	Point addPoints(Point one, Point two)
	{
	    return new Point (one.x+two.x,one.y+two.y);
	}
	
	Point up(Point one, Point two, double scale)
	{
	     int x = (int) (scale*(two.x-one.x));
	     int y = (int) (scale*(two.y-one.y));
	     return addPoints(one, new Point(x,y));
	}
	
	Point rotate(Point one,Point two)
	{
	    Point p = up(one,two, 1.0/2);
	    int y = (int)((one.x - two.x)/4.0 );
	    int x = (int) ((two.y- one.y)/4.0);
	    return addPoints( p, new Point(x,y));
	}   
	    
	public void drawFractal(Point b,Point e, int d, Graphics g)
	{
	    if (d == 0) g.drawLine(b.x,b.y,e.x,e.y);
	      else
	     {
	        Point next = up(b,e,1.0/4);
	        Point mid = rotate(b,e);
	        Point last = up(b,e,3.0/4);
	        drawFractal(b,next, d-1,g);
	        drawFractal(next,mid,d-1,g);
	        drawFractal(mid,last,d-1,g);
	        drawFractal(last,e,d-1,g);
	   	 }
	}
	
	public void paint(Graphics g)
	{
	  g.setColor(Color.blue);
	  Point begin = new Point(100,200);
	  Point end = new Point(500,200);
	  int depth = 4;     // How deep is too deep?
	  drawFractal(begin,end,depth, g );
	}
}