Fundamentals of Computer Science II (CSC-152 98S)

[Instructions] [Search] [Current] [Changes] [Syllabus] [Handouts] [Outlines] [Labs] [Assignments] [Examples] [Bailey Docs] [SamR Docs] [Tutorial] [API]


Lab 13: Drawing an April Fool

Held: Wednesday, April 1, 1998

Goal: Your goal in this lab is to devlop a face-drawing applet in which one can specify the "parameters" of the face (feature sizes, complexion, etc.) in a separate HTML file. Yes, that's right, the goal of our lab will be to develop a customizable April fool.

In this laboratory session, you will develop one or more Java applets which are displayed in web pages. The purposes of this lab session are to

Prerequisite skills:

Disclaimer: I've included this lab in the course as a lark. I originally wrote a variant for CS103 and partially targetted it toward a lab manual I'm writing. I thank you in advance for serving as "test subjects" for the lab.

Required HTML files:

To make a copy of an HTML file, click and hold on the link above with your right mouse button. Eventually, a menu will appear. Select save link as and then select where to save the HTML file. You can use the same process for the Java files below.

Required Java files:

Contents


Discussion

Applets

In addition to supporting the standard application model of programming, Java also supports a variant model, known as the applet model. Applets are programs that are designed to be run within other programs. Most often, applets are graphical programs that run within web pages. In this session, we'll focus on the static applets.

Interestingly, the structure of an applet differs from that of an application. In particular, applets do not contain constructors or a main method. Rather, they use alternate methods to support the same concepts (of initialization and execution). These alternate methods are:

In order for the Java interpreter or web browser to successfully execute an applet, you need to tell Java that your class describes applets (as opposed to other things). You do this by including the phrase

extends Applet
in your class header.

For example, I might write

public class MyCoolApplet
  extends Applet {

In addition, you must tell Java that you'll be using the various applet and graphics libraries. You do this with a series of import statements.

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

To include a Java applet within a web page, you use the applet tag. Within the tag, you need to specify the code file for the applet and the width and height of the applet. For example, the following creates a 400 by 300 area for the applet CircleApplet.

<applet code="CircleApplet.class" width="400" height="300">
</applet>
Note that you do need an end tag for applets. Later, we will see things that can go between the two tags.

Painting Pictures

You are almost ready to build your first applet. However, you will first need to learn how to paint. Java provides a class, java.awt.Graphics, that provides most of the core painting routines. If your instructor has provided you with a copy of the Java API (Application Programmer Interface), you may wish to refer to the section of the API that covers the Graphics class as we'll only cover a few of the many routines that class provides.

To draw anything in Java, you will first want to set the color of the pen that does the drawing. You do that with a call to setColor. What color's can you use? They are specified within java.awt.Color. For now, you should use Color.red, Color.blue, and Color.green. If your current graphics object is named g, you would indicate that the pen color should be set to green with

g.setColor(Color.green);

Java permits you to draw a number of different objects, including circles and ovals, squares and rectangles, lines, and pieces of text. You draw the outline of a circle or oval with

g.drawOval(int left, int top, int width, int height);
That is, you specify the farthest left side point on the oval, the top point on the oval, the width of the oval, and the height of the oval. You can fill in the oval with g.fillOval, which has the same parameters.

Java uses an interesting coordinate system. The top-left corner of a drawing area is (0,0) and coordinates increase down and to the right.

Other routines you may want to use include

A Circle Applet

Building applets that draw pictures is relatively easy. All such applets need to contain is Here is a simple applet that draws a small circle on the screen. Note that all it contains is a paint method that sets the color and calls g.fillOval.

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

/**
 * Draw a small blue circle on the screen.
 * <p>
 * Copyright (c) 1998 Samuel A. Rebelsky.  All rights reserved.
 *
 * @author Samuel A. Rebelsky
 * @version 1.0 of March 1998
 */
public class CircleApplet extends Applet {
  /**
   * Paint a blue circle on the screen.
   */
  public void paint(Graphics g) {
    // Paint a circle of diameter 40
    g.setColor(Color.blue);
    g.fillOval(0,0,40,40);
  } // paint(Graphics)
} // CircleApplet

Exercise: Do experiment G1.1.

Colors

As you can tell from the previous experiment, Java supports a few different predefined colors, including Color.red and Color.blue. The available colors are black, blue, cyan, darkGray, gray, green, lightGray, magenta, orange, pink, red, white, and yellow. You can also create your own color using

new Color(int red, int blue, int green);
In which each of the three color components is a number between 0 and 255.

Exercise: Do experiment G1.2.

Applet Dimensions

You may have noted that the dimensions (width and height) of an applet are set within the HTML files that loads the applet and not within the applet itself. Clearly, it is possible to load the same applet with different dimensions and different pages may therefore choose different dimensions for the same applet. For many applets, it becomes important for the applet designer to be able to determine these dimensions.

Fortunately, Java provides a mechanism for the applet author to determine the dimensions given for the applet. You can call this.getSize() to obtain a Dimension object. You can then get the width of that object by referring to its width and height fields.

Here is a sample applet that uses the dimension to paint a blue oval that is the full width and height of the applet area.

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

/**
 * Draw a circle on the screen.
 * <p>
 * Copyright (c) 1998 Samuel A. Rebelsky.  All rights reserved.
 * 
 * @author Samuel A. Rebelsky
 * @version 1.0 of March 1998
 */
public class FullCircleApplet extends Applet {
  /**
   * Paint a blue circle on the screen.
   */
  public void paint(Graphics g) {
    // Get the dimensions of the applet
    Dimension dim = this.getSize();
    // Paint a circle
    g.setColor(Color.blue);
    g.fillOval(0,0,dim.width,dim.height);
  } // paint(Graphics)
} // FullCircleApplet

Exercise: Do experiment G1.3.

Repainting

Interestingly, Java repaints the screen every time the applet window is resized (or another window is moved over the window or ...). What does it mean to repaint the screen? It means that Java erases what's there (or at least spreads some of the "background color" over what the applet has painted) and then calls the paint method again. You can use this to your advantage. How? By changing the way you draw your picture each time.

For example, we might make an applet in which the circle moves down and to the right each time the picture is redrawn. Doing so requires us to add fields to our applet (e.g., the x and y position of the current circle). We will also need to initialize those fields (aha! a use for that init method we saw much earlier). Here is a sample applet that draws a circle in a slightly different position at each step.

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

/**
 * Draw a small blue circle on the screen.  Move it whenever the
 * window is repainted.
 * <p>
 * Copyright (c) 1998 Samuel A. Rebelsky.  All rights reserved.
 *
 * @author Samuel A. Rebelsky
 * @version 1.0 of March 1998
 */
public class MovingCircleApplet extends Applet {

  // +--------+--------------------------------------------------
  // | Fields |
  // +--------+

  /**
   * The position of the left edge of the circle.
   */
  protected int left;

  /**
   * The position of the top edge of the circle.
   */
  protected int top;


  // +----------------+------------------------------------------
  // | Applet Methods |
  // +----------------+

  /**
   * Initialize the applet (set the top-left of the circle to (0,0)).
   */
  public void init()
  {
    top = 0;
    left = 0;
  } // init()

  /**
   * Paint a blue circle on the screen.
   */
  public void paint(Graphics g) {
    // Paint a circle of diameter 40
    g.setColor(Color.blue);
    g.fillOval(top,left,40,40);
    // Increment top and left for the next repainting
    top = top + 15;
    left = left + 15;
  } // paint(Graphics)

} // MovingCircleApplet

In a typical applet, there are a number of things we might choose to do at each redraw. We might move objects. We might change colors. We might add or delete objects. "The sky's the limit" as it were. Note also that by updating our image we have begun to provide a form of animation. We will revisit animation in a later lab.

Exercise: Do experiment G1.4.

Applet Parameters

In addition to using the HTML document to set the dimensions of an applet, you can also use the document to set other attributes of the applet. These are often called the applet's parameters. What can the parameters be? Anything you thing is appropriate. For our circle-drawing applications, they might be the position, size, or color of the circle. They might even specify which shape we use (although we only know a few right now).

How do you set a parameter? With a param tag (which goes between your applet tags). Here's a tag that indicates that the value of the printMe parameter is "Java Rocks!".

<param name="printMe" value="Java Rocks!">

How can you access that parameter? With a getParameter method. The getParameter method always returns a string (even if you want a number). If the HTML code does not include a param tag with the appropriate name, getParameter returns null.

What happens if you want some other type (e.g., an integer)? If you need to convert the parameter to another type you'll need to use some slightly tricky Java. For now, rely on the function included in the sample code below.

Here's a simple applet that displays a piece of text in a color selected by its red, green, and blue components.

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

/**
 * Draw some colored text on the screen.  Intended as an illustration
 * of applet parameters.
 * <p>
 * Copyright (c) 1998 Samuel A. Rebelsky.  All rights reserved.
 *
 * @author Samuel A. Rebelsky
 * @version 1.0 of March 1998
 */
public class ColoredTextApplet extends Applet {
  
  // +--------+------------------------------------------------------------
  // | Fields |
  // +--------+

  /**
   * The color of the text.
   */
  protected Color color;

  /**
   * The text to print.
   */
  protected String text;


  // +----------------+----------------------------------------------------
  // | Applet Methods |
  // +----------------+

  /**
   * Initialize the color and text.
   */
  public void init() {
    // The three components of the color
    int red;
    int green;
    int blue;

    // Get the text
    text = getParameter("printMe");
    if (text == null) {
      text = "Jabberwocky";
    }
    
    // Get the color
    red = getIntegerParameter("red");
    green = getIntegerParameter("green");
    blue = getIntegerParameter("blue");
    color = new Color(red, green, blue);
  } // init()

  /**
   * Paint the text on the screen.
   */
  public void paint(Graphics g) {
    // Paint a circle of diameter 40
    g.setColor(color);
    g.drawString(text,10,40);
  } // paint(Graphics)


  // +-----------+---------------------------------------------------------
  // | Utilities |
  // +-----------+

  /**
   * Get a parameter and convert it to an integer.  If the
   * parameter is unspecified or otherwise bad, use 0.
   */
  protected int getIntegerParameter(String param_name)
  {
    // Get the value of the parameter
    String param_value = getParameter(param_name);
    // If the parameter is unspecified, use 0
    if (param_value == null) return 0;
    // Attempt to convert to an Integer.
    try {
      return Integer.parseInt(param_value);
    }
    catch (Exception e) {
      return 0;
    }
  } // getIntegerParameter(String)

} // ColoredTextApplet


Real Exercise: Face Drawing

Finally! We've reached the main intent of the lab. (However, you may want to do some preparatory experiments first.)

Create an applet, FaceApplet, that draws a face according to the parameters specified in the accompanying HTML file. The parameters might include size and color of features, optional features, complexion, and anything else you deem appropriate.

Here's a sample applet tag for the applet.

<applet code="FaceApplet.class" width="100" height="150">
<param name="eyecolor" value="blue">
<param name="eyesize" value="small">
<param name="glasses" value="yes">
<param name="expression" value="surprised">
</applet>

You may want to start by drawing a simple face and then taking into account parameters, one by one. You may find it easier to start by drawing an oval (the face) whose general form is specified by a parameter and then add features one-by-one. It's up to you.

Once you've written your applet, paste it here and click the submit button. I'll try to set up a common repository of your face drawing applets.

Name:
Email:


Preparatory Experiments

Name:
Email:

Experiment G1.1: A Colored Circle Applet

Step 1. Make copies of CircleApplet.java and Circle.html. Compile CircleApplet. Then run appletviewer on Circle.html. Note what you see.

Step 2.

Open Circle.html from within your internet browser (e.g., Netscape) and note what you see. Is there a significant difference between the two versions?

Step 3.

Modify CircleApplet.java so that it draws a second red circle whose center is ten spaces to the right and five spaces down from the center of the first circle. Recompile your code and then reload the applet. Where you able to successfully position the circle? Which one is on top? Why?

Experiment G1.2: Experimenting with Colors

Step 1. Using your CircleApplet class, try to figure out how much red, how much green, and how much blue you need to create a satisfactory purple. It is presumably better to create a large number of circles and fill each with a different color. Once you have determined the color, write it here.

Step 2. Using your CircleApplet class, try to make a sequence of shades of orange such as one might see in a custom paint shop.

Experiment G1.3: Getting Boundaries

Step 1. Make a copy of FullCircleApplet.java. Compile FullCircleApplet. Modify Circle.html to load this new applet instead of CircleApplet. Then load the applet with appletviewer. What do you see? Is that what you expected?

Step 2. Modify Circle.html so that the width of the applet is 100 and the height is 10. Do not recompile FullCircleApplet. Load the applet with appletviewer. What do you see? Is that what you expected?

Step 3. Load Circle.html with appletviewer. If you click on one of the edges of the applet window, you should be able to resize the window. Does the circle resize when the applet size changes? What, if anything, does this suggest?

Step 4. If we were to draw four circles of radius 10 in the four corners of the window, what would their positions and width and height be? Once you've determined (and written down) these position, extend FullCircleApplet.java to draw these four small circles in the corners. If you miscomputed some positions or sizes indicate which ones and analyze why.

Experiment G1.4: Repainting

Step 1. Make a copy of MovingCircleApplet.java. Compile MovingCircleApplet. Modify Circle.html to load this new applet instead of CircleApplet. Then load the applet with appletviewer. What do you see? Is that what you expected?

Step 2. Resize the window. What happens to the circle? Is that what you expected? Why or why not?

Step 3. Move another window over the circle. Then move it away. What happens to the circle? Is this what you expected? Why or why not?

Step 4. Move another window over the appletviewer window, but not over the circle. Then move it away. What happens to the circle? Is this what you expected? Why or why not?

Step 5. Shrink and then expand the window. What happens to the circle? Is this what you expected? Why or why not?

Step 6. See if you can determine other ways to make the circle move. List them here.

Experiment G1.5: Setting Parameters

Step 1. Make a copy of ColoredTextApplet.java and ColoredText.html. Compile ColoredTextApplet and run appletviewer on ColoredText

What do you see? Is that what you expected?

Step 2. Using your determination of the color purple from a previous exercise, modify ColoredText.html so that it displays your name in purple.

Step 3. Update ColoredTextApplet.java so that it changes the color each time it redraws. To support this, you will need to make the red, green, and blue components fields of the class and to create a new color each time. Increment each component by ten at each redraw. What happens when one of the three component colors gets a value over 255? After noting any problems, fix your class so that none of the components gets a value outside of 0 to 255.

Step 4. Remove the param tag that sets the red value value. What do you expect to happen? What does happen?

Step 5. Remove all of the param tags. What do you expect to happen? What does happen?

Wrapup

You should feel no obligation to submit your answers. However, if you choose to do so you will receive a copy via email (for your own records).


[Instructions] [Search] [Current] [Changes] [Syllabus] [Handouts] [Outlines] [Labs] [Assignments] [Examples] [Bailey Docs] [SamR Docs] [Tutorial] [API]

Disclaimer Often, these pages were created "on the fly" with little, if any, proofreading. Any or all of the information on the pages may be incorrect. Please contact me if you notice errors.

Source text last modified Wed Apr 1 08:05:01 1998.

This page generated on Wed Apr 1 08:09:57 1998 by SiteWeaver.

Contact our webmaster at rebelsky@math.grin.edu