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:
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:
public void init(), which specifies
how to initialize your applet. In effect, init serves
as the constructor for an applet.
public void run(), which starts
your applet. In effect, run serves as the
main for your applet.
public void paint(Graphics g), which
paints a picture on the screen. Since most applets are graphical,
the paint method is often the core of an applet.
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
in your class header.extends Applet
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.
Note that you do need an end tag for applets. Later, we will see things that can go between the two tags.<applet code="CircleApplet.class" width="400" height="300"> </applet>
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
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 withg.drawOval(int left, int top, int width, int height);
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
g.drawRect(int left, int top, int width, int height)
g.fillRect(int left, int top, int width, int height)
g.drawLine(int x1, int x2, int y1, int y2)
g.drawString(String str, int x, int y)
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.
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
In which each of the three color components is a number between 0 and 255.new Color(int red, int blue, int green);
Exercise: Do experiment G1.2.
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.
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.
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
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.
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