Experiments in Java


Session G1: Graphics and Applets

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 the first lab session, you may have experimented with applets that drew pictures on the screen or animated balls or balloons. 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 typically 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:

(Note that some programmers write Java applets that are also applications, or vice versa. In this case, the classes are likely to include constructors, init, and main.)

In order for the Java interpreter or Web browser to run an applet successfully, 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 will 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 colors 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 paintBrush, you would indicate that the pen color should be set to green with

    paintBrush.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

    paintBrush.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 paintBrush.fillOval, which has the same parameters.

Other routines you may want to use include

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.

A circle applet

Building applets that draw pictures is relatively easy. All such applets need to contain is a paint method. 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 paintBrush.fillOval.


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

/**
 * Draw a small blue circle on the screen.
 *
 * @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 paintBrush) {
    // Paint a circle of diameter 40
    paintBrush.setColor(Color.blue);
    paintBrush.fillOval(0,0,40,40);
  } // paint(Graphics)
} // class CircleApplet


In Experiment G1.1, you will run this simple applet and make some basic modifications.

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 green, int blue);

Each of the three color components is a number between 0 and 255. For example, you might set the pen to an interesting shade of green with

    Color myColor = new Color(0, 200, 255);
    paintBrush.setColor(myColor);

You might also use the more succinct

    paintBrush.setColor(new Color(0, 200, 255));

In Experiment G1.2, you will experiment with different mechanisms for creating colors.

Pixels vs. coordinates

You have already noticed that Java's coordinate system is somewhat odd. In particular, while horizontal coordinates increase to the right, vertical coordinates increase as you move downward. Yet this is not the only way in which Java's drawing conventions defy many beginning programmers' initial assumptions.

Surprisingly, the coordinates on the grid are not where the ink appears. Rather, the ink appears between these points. For example, the top-left pixel is not at (0,0). Rather, it appears between the four points (0,0), (0,1), (1,0), and (1,1).

Why does this make a difference? Because fillRect and fillOval color only the pixels within the area described by the parameters, whereas drawRect and drawOval color the pixels to the left and down from the object described. For example, the lower-right pixel drawn by fillRect(0,0,3,2) is bounded by (2,1), (2,2), (3,1), and (3,2). However, the lower-right pixel drawn by drawRect(0,0,3,2) falls to the right of and below the lower-right corner (3,2) and therefore is bounded by (3,2), (3,3), (4,2), and (4,3). What is the moral? Filled shapes are typically one pixel smaller horizontally and vertically than drawn shapes. In Experiment G1.3, you will consider this difference.

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.Applet;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

/**
 * Draw a circle on the screen.
 * 
 * @author Samuel A. Rebelsky
 * @version 1.1 of August 1999
 */
public class FullCircleApplet extends Applet {
  /**
   * Paint a blue circle on the screen.
   */
  public void paint(Graphics paintBrush) {
    // Get the dimensions of the applet
    Dimension dim = this.getSize();
    // Paint a circle
    paintBrush.setColor(Color.blue);
    paintBrush.fillOval(0,0,dim.width,dim.height);
  } // paint(Graphics)
} // class FullCircleApplet


In Experiment G1.4, you will work with applets that behave differently depending on the boundaries that they are given.

Repainting

Interestingly, Java repaints the screen every time the applet window is resized (or another window is moved over the window, etc.). Repainting the screen means that Java erases what is already 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 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 positions 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.
 *
 * @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 paintBrush) {
    // Paint a circle of diameter 40
    paintBrush.setColor(Color.blue);
    paintBrush.fillOval(top,left,40,40);
    // Increment top and left for the next repainting
    top = top + 15;
    left = left + 15;
  } // paint(Graphics)

} // class MovingCircleApplet


In a typical applet, we might choose a to do a number of things 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.

In Experiment G1.5, you will investigate some capabilities of the paint method for redrawing.

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 think 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.

You set a parameter with a param tag, which goes between your applet tags. The following tag indicates that the value of the printMe parameter is ``Java Rocks!''.

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

How can you access that parameter? With the 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 the special null value.

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.

The following simple applet 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.
 *
 * @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 paintBrush) {
    // Paint a circle of diameter 40
    paintBrush.setColor(color);
    paintBrush.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)

} // class ColoredTextApplet


In Experiment G1.6, you will begin to consider the use of parameters in applets.


Copyright (c) 1998 Samuel A. Rebelsky. All rights reserved.

Source text last modified Mon Oct 25 22:33:27 1999.

This page generated on Tue Oct 26 15:38:38 1999 by Siteweaver.

Contact our webmaster at rebelsky@math.grin.edu