Java Student Project       



Applet Example (requires JRE 1.3.1+)

Text Animation
Ability Level:
Intermediate
Estimated Time: 30 minutes
Objectives:
  • Learn basic Java Animation Concepts
  • Learn to use arrays for animation

Materials & Resources:
  • Java Software
  • Java Textbook

Overview:
         Write a program that animates a String and
         makes another String change colors
Instructions:

1. Create a program that makes a Frame (window)

2. Make an int[] array for the positioning of the moving String
and a Color[] array for the color changing String

3. Read the hints section if you have questions about the following code

// Text Animation by Your Name

import java.awt.*;
import java.awt.event.*;

public class textAnime extends Frame
{
  private int sleep = 100;
  private int index = 0;
  // declare position/color arrays

  public static void main(String[] args)
  {
    textAnime win = new textAnime();
    win.show();
  }

  textAnime()
  {
    // insert basic options: size, title, etc...
    addWindowListener(new WindowAdapter() {
      public void windowClosing(ActionEvent e) { // if attempt to close the window
        dispose();      // close the window
        System.exit(0);      // kill entire program
      }
    });
  }

  public void paint(Graphics gr)
  {
    // Insert the Strings Here with drawString

    ++index;
    // if index == length of arrays
      // make index = 0 for the loop

    // following try/catch will pause it before each loop; minimizing flickering
    try {
      Thread.sleep(sleep)
    }
    catch(InterruptedException e) {}

    repaint();
  }
}

Hints:

1. Use an index variable for calling arrays. example:

private int index = 0;
/* Insert Paint Method here */
gr.drawString("something", xvar[index], yvar[index]);

2. Rember setColor expects a color value to be passed through it. Declaring a String[] array is not a color array. example:

String[] colors = { "Color.red", "Color.blue", "Color.green" }; <-- not valid
Color[] colors = { Color.red, Color.blue, Color.green }; <-- valid color array

3. Here is an example of a basic animation with an array.

private int index = 0;
int[] xvar = { 1, 2, 3, 4 };
int[] yvar = { 1, 2, 3, 4 };

public void paint(Graphics gr)
{
  gr.drawString("something", xvar[index], yvar[index]);

  ++index;
  if (index == xvar.length || index == yvar.length)
    index = 0;
}