Updated: 2005/10/22

Abstract Art: Creating Shapes and Animation with Java


Sources:

Much of this lab is based on the Java Sun on-line tutorial lesson, Working With Graphics. The source code you will be using, ArtLab.java, is a modified version of their MovingImageTimer.java.


Contents:


Objectives

In this lab you will gain a general understanding of how you can use computer programming to create basic shapes and animation. You will be introduced to Java's Graphics2D class and its capabilities.


Lab Overview

This lab is an introduction to using programming to create art and animation. Java has a Graphics2D class, this class allows you to draw primitive shapes such as circles, ovals, squares, rectangles and lines, and outline or fill them with different colors. You will use this class to draw your own abstract picture, use loops and if statements to create patterns with shapes, and then use a timer to add animation.


Before the Lab

Before the lab you should read over these lab instructions and review your notes from class. Be sure to read the entire lab, not just the 'Before the Lab' section.  You should have experience using WordPad and a general understanding of Java. This section will provide an overview of the source code we will be using, ArtLab.java, as well as some general information on working with graphics in Java.

  1. The Source Code
  2. The general structure of ArtLab.java is:

                public class ArtLab extends JApplet implements ActionListener
                {
                ...
                here is the code that sets up and displays our panel
                ...

                      public class AnimationPane extends JPanel
                      {
                      ...

                            public void paintComponent(Graphics g)
                            {
                            ...
                            this is where we will add the code to draw our shapes
                            ...
                            }

                      ...
                      here are the methods used for animation
                      ...
                      }

                ...
                here is the "main" method used to start up the program
                ...
                }

    If you would like to view all the code at this point, download the file ArtLab.java and open the file in a text editor such as WordPad or Notepad.  ArtLab.java has a few different parts to it. There is the main class called ArtLab, and within that a subclass called AnimationPane. You will only be modifying the paintComponent method in the AnimationPane class. You do not need to understand anything except what is in the paintComponent method, but you can take a look at the other stuff if you want to.

  3. The Coordinate System
  4. When you draw your shapes on-screen, Java places them according to a 2-dimensional xy coordinate system based on pixels. The x-axis runs horizontally and the y-axis vertically, as illustrated below:

    Source: Java Sun on-line tutorial "Working With Graphics"

    The x-axis increases to the right, and the y-axis increases downwards. The convention used for coordinates notation is (x, y), you may remember this from math class. The Drawing Panel you will use is 800 pixels wide by 550 pixels high, so the panel's coordinates will be:

  5. The Colour Class

  6. Java has a class called Color, which you'll use to paint your shapes. Within the paintComponent method, you can see the following code:

                //set the colors
                            Color black = Color.black;
                            Color blue = Color.blue;
                            Color gray = Color.gray;
                            Color red = Color.red;
                            Color yellow = Color.yellow;
                            Color orange = Color.orange;
                            Color cyan = Color.cyan;
                            Color green = Color.green;
                            Color magenta = Color.magenta;
                            Color white = Color.white;
                            Color pink = Color.pink;

    This code is declaring a color that's called "black" (for instance) and then setting that color to be equal to the black member of the Color class (Color.black means the black object in the Color class). This allows you to use the word black, and have the computer know that you are referring to the color black in the Color class. In this lab, these are the colors available for you to use.


  7. The Graphics2D Class
  8. The Graphics2D class has methods which allow you to draw and set the color of many primitive shapes. Here is a summary of the methods you can use in this lab (you will see how to use them in the During the Lab section):

    All of the parameters for each these methods must be integers (whole numbers). All of the draw* methods draw an outline of the specified shape, while the fill* methods draw the shape and fill it with the current color. When specifying the width and height parameters for the draw* methods, you should specify 1 pixel less than what you desire (the method draws a border around the width and height specified). However, for the fill* methods you should use the exact pixel-size.

    If the x or y parameters to these methods are negative or outside the bounds of the screen (800 wide and 550 high), the shapes will not be displayed.

     

During the Lab

Part 0: Setting the Compiler Path

  1. Click on the Start menu, then on Settings, then on Control Panel.
  2. Double click on System, then click on the Advanced tab.
  3. Now click on the Environment Variables... button.
  4. Under the User Variables section, double click on the variable named path. If this variable does not exist, click the 'New' button and enter path as the variable name
  5. In the Variable Value field, type C:\Program Files\Java\jdk1.5.0_04\bin (Don't put any extra blank space after "bin").
  6. Click on Ok, then Ok again, and finally Ok once more to close the System box.
  7. Now you need to restart your computer, click on the Start menu, then Shut Down... then Ok to logoff. Now log back on.

Part I: Download ArtLab.java to your home directory (the Z drive) if you haven't already done so. This code needs to be directly on your Z drive (i.e, not within a folder that's on your Z drive).

Open the file in WordPad. Don't be worried if this code seems very confusing, there is a lot code that you don't need to worry about.

 

Creating Shapes

  1. A Solid Yellow Circle
  2. Now you'll write the code to draw a solid yellow circle, and place it near the upper left corner of the screen. The circle will have a diameter of 200 pixels, and the x-y coordinates (50, 50). Scroll down in ArtLab.java until you see the line:

                                        //draw the shapes

    Underneath this line is a large blank area, this is where you'll add the code to create your shapes. Beginning on the next line, type:

                                        //yellow circle
                                        newShape ( );
                                        x = 50;
                                        y = 50;
                                        width = 200;
                                        height = 200;

    The first line you typed was a comment (that's what the // signals). This is just to make your code easier to read and understand. Then you called the newShape method; this method has been written for you to reset the graphics settings. You should call this method each time you create a new shape.

    In the 3rd and 4th lines, you are assigning the shape's x and y variables to both be equal to 50. This will place the circle's upper-left corner at the point (50,50). Since you are drawing a circle, its width and height should be the same (i.e., its diameter). We want a diameter of 200 pixels, so in the 5th and 6th lines you assign the width and height variables to this value.

    Now you have to specify the shape's color. All of the shapes and their attributes are part of the Graphics2D class, the instance of this class we'll be using has been named g2. So to set the color of this shape (which is part of g2), start a new line and type:

                                        g2.setPaint (yellow);

    Finally, on the next line type the code to actually draw the circle:

                                        g2.fillOval(x, y, width, height);

    This line calls the fillOval method as discussed in the previous step. The variables x, y, width and height are used as its parameters.

    Save your work, then open a Command Prompt using the Start Menu (click on Start | Program Files | Accessories | Command Prompt). To get to your directory, type:

                                        Z:

    and press Enter. Now we need to compile the ArtLab.java file. To do this, type:

                                        javac ArtLab.java

    and press Enter. Once the computer is finished compiling (and there are no errors), run your program by typing:

                                        java ArtLab

    If you get an error when you do this, instead try

                                         java -classpath ./ ArtLab

    and press Enter. After you have admired your handiwork, close the drawing panel and minimize the Command Prompt.


  3. A Red Rectangle
  4. Next you'll add a solid red rectangle. Press Enter twice to put a space between the code for your circle and rectangle (to make it easier to read). Your rectangle can be placed anywhere on the screen you like (remember the screen is 800 x 550), and be any width and height. In the code below, the rectangle will be placed at the coordinates (550, 400) and be 200 pixels wide and 100 pixels high, but you can change these numbers. Following the format of the previous step, type:

                                        //red rectangle
                                        newShape ( );
                                        x = 550;
                                        y = 400;
                                        width = 200;
                                        height = 100;
                                        g2.setPaint (red);
                                        g2.fillRect (x, y, width, height);

    Save your file, then go to the Command Prompt and compile it by typing (make sure you are at the Z drive, if not type Z: and press Enter):

                                        javac ArtLab.java

    and press Enter. Once it has compiled successfully, run it by typing:

                                        java ArtLab

    and press Enter. Close the Drawing Panel and minimize the Command Prompt when you are finished looking at your work. You can experiment by changing the size and placement of your rectangle.


  5. An Orange Line
  6. To draw lines, it's a little different (they have no width or height parameters). You're going to add an orange line to the program, you can place it anywhere you like (just change the numbers in the code below). To draw a line, press Enter twice and type:

                                        //orange line
                                        newShape ( );
                                        x1 = 500;
                                        y1 = 200;
                                        x2 = 700;
                                        y2 = 10;
                                        g2.setPaint (orange);
                                        g2.drawLine (x1, y1, x2, y2);

    The x1 and y1 variables are the line's starting coordinates, and the x2 and y2 are the coordinates for its end.

    Save, compile and run your program (see steps 6 or 7 if you forget how).


  7. A Magenta Oval
  8. As you noticed in the last step, when you use the draw* methods, the computer draws a rather thin line. Now you'll draw a magenta oval, but make the computer use a thick line. Once again, you can make it any size and put it anywhere. As before type:

                                        //magenta oval
                                        newShape ( );
                                        x = 300;
                                        y = 200;
                                        width = 120;
                                        height = 75;
                                        g2.setPaint (magenta);

    Now to set the stroke size (the line thickness) on the next line type:

                                        g2.setStroke (wideStroke);

    Finally, to finish the oval off, start a new line and type:

                                        g2.drawOval (x, y, width, height);

    Save, compile and run your program.


  9. A Green & Blue Square
  10. In this step you'll add a square, but with some fancy coloring. You'll use the GradientPaint capability of the Graphics2D class to make the square's color fade from green to blue. Your square can be any size, and placed anywhere on your screen. Put a space between the previous shape and this one and type:

                                        //green & blue square
                                        newShape ( );
                                        x = 120;
                                        y = 350;
                                        width = 100;
                                        height = 100;

    Now you are going to use a method called Fade to make the fancy paint. This method has two parameters: the colors you want to use. To use this method, you type Fade(color1,color2), where color1 and color2 are the colors of your choice. The next step is to set the current graphics color to the paint created by this method. On the next line type:

                                        g2.setPaint ( Fade(green, blue) );

    Finally, on the next line type:

                                        g2.fillRect (x, y, width, height);

    Save, compile and run your program.


  11. A Little Creativity
  12. Spend a couple of minutes exploring your creative side.  Experiment with the size and placement of your shapes and try adding some new ones.

    It's easy to change the background color if you want to, scroll upwards until you see the text:

                                        //draw the background
                                                    g2.setPaint (black);
                                                    g2.fillRect (0, 0, screenWidth, screenHeight);

You can change the color in the setPaint method.

Here are things you can try:

As a minimum, your program must display these requirements:

  1. One of each of the following shapes:
    • circle or oval
    • square or rectangle
    • line
  2. At least one of the shapes must be painted with a thick line.
  3. At least one of the shapes must have 2-color gradient paint.

 

Part II: Patterns

  1. Pattern of Circles

In this step, you'll make a pattern using the while loop. The while loop allows you to repeat a sequence of statements for a specific number of times. In this example, you are going to draw ten circles. Type:

                                //pattern of circles
                                int counter;
                                g2.setPaint ( green );

Here, 'int counter;' declares a variable called 'counter' that we will use to control the number of iterations of our while loop. In the following while loop, the counter starts at zero and is increased by one in each step before it reaches ten. In each step, a circle is drawn. Since the y coordinates of the circles depend on the counter, each circle is drawn at a different position. 

counter = 0;
while (counter < 10)
{
    newShape();
    x = 650;
    y = 20 + counter * 30;
    width = 100;
    height = 100;
    g2.drawOval(x, y, width, height);
    counter = counter + 1;
}

Save, compile and run your program.

 

  1. Pink and Cyan Rectangles

Now, you'll make a pattern of rectangles using the if statement. You want the rectangles to have alternating colours. Type on the next line:

// Pink and cyan rectangles
counter = 0;
while (counter < 10)
{
        newShape ();

If the counter is even, the rectangles are pink. Otherwise, the rectangles are cyan. (counter % 2) gives you the remainder of counter / 2. The counter is even when the remainder is zero.

        if ( (counter % 2) == 0)
        {
                g2.setPaint ( pink);
        }
        else
        {
                g2.setPaint ( cyan);
        }

The coordinates, lengths, and widths of the rectangles are dependent on the counter. As a result, the rectangles have different sizes and positions.

        x = 250 + counter * 20;
        y = 250 + counter * 20;
        width = counter * 10;
        height = counter * 10;
        g2.drawRect(x, y, width, height);
        counter = counter + 1;
}

Save, compile and run your program.

 

  1. Your Own Pattern

Now it's time to create your own pattern. In what ways can you combine shapes and patterns? You are required to use the while loops and the if statements to generate some interesting patterns. Click here for some examples of patterns.  Try creating a checkerboard or another interesting design.  You pattern should make use of at least two loops/if statements.

     


Deliverables

  1. Demonstrate your graphics program to the lab TA. As stated in Part I step 6, your program must display at least the following requirements:
  1. Show your TA the pattern you created in Part II.  Remember to use at least two different loops or and/or if statements.
  1. The lab will be marked as follows: Part 1: circle or oval (1 mark), square or rectangle (1 mark), line (1 mark), at least one shape painted with a think line (1 mark), some shape with 2 colour gradient (1 mark), creativity (2 marks). Part II: at least two control flow (if or while) statements (2 marks); creativity (1 mark).

After the Lab

Once you have completed Parts I and II of During the Lab, if you have time, we strongly encourage you to continue with the following section to learn how to add animation to your graphics program. (This is not only good fun, but will also help you improve your understanding and command of this material in a playful way!)

Part III: Adding Animation

  1. How it Works
  2. Now you'll do some coding to enable your shapes to move across the screen. Within the ArtLab class, there is a timer and an integer variable named frameNumber. Once your program starts, the timer starts running and doesn't stop until the program ends. After a specified amount of time (in the range of milliseconds), the timer causes the computer to increase frameNumber by one, and repaint all of the shapes. If you make the shapes' coordinates depend on frameNumber (which is continually increasing with time) the coordinates will also depend on time. As time increases, the coordinates (where the shapes are drawn on-screen) will change and your shapes will move.

    Note: Clicking your mouse in the Drawing Panel will start and stop the animation.

    Since animation uses lots of processor cycles, the refresh rate for the animation is currently set to be very slow. If you get to this part of the lab, you may set the refresh rate to be faster. To do this, find the line

                                        int delay = (fps > 0) ? (1000 / fps) : 100000;

    near the top of your code, and change the number 100000 to 100. (Remember not to remove the semicolon (;)).


  3. Moving Forward in A Horizontal Line
  4. You are going to make the yellow circle move forwards in a horizontal line along the drawing panel. We want the x-coordinate to increase with time, and the y-coordinate to be constant. To do this, we will use a method called xFwdLine which uses a mathematical expression involving frameNumber to calculate what the x-coordinate should be in order to move it across the screen. The xFwdLine method has two parameters. The first is the x-coordinate that you want the shape to start from, and the second is the speed at which you want the shape to move (a greater number gives faster movement). Both parameters must be an integers (cannot have decimals). To use this method you would type, xFwdLine(start,speed). Go to the yellow circle's code in your program, you should see code similar to this:

                                        //yellow circle
                                        newShape ( );
                                        x = 50;
                                        y = 50;
                                        width = 200;
                                        height = 200;
                                        g2.setPaint (yellow);
                                        g2.fillOval (x, y, width, height);

    You're going to change the x variable so that it's assigned the result of xFwdLine. Change this line to look like:

                                        x = xFwdLine (50, 15);

    In the line above, the circle will start at the x-coordinate of 50 pixels, with a speed of 15, feel free to change these numbers. Save, compile and run your program to see your animated circle.


  5. Moving Backward in a Diagonal Line
  6. In addition to the xFwdLine method, there are also the xBwdLine, yFwdLine and yBwdLine methods. The xBwdLine is similar to xFwdLine, except that the shape will move backwards in the x-direction. The yXxxLine methods do the same things, only for the y-coordinate. To make the red rectangle move backwards in a diagonal line, you'll use both the xBwdLine and yBwdLine methods. The parameters for these methods are the same as above, the first is the starting coordinate and the second is the speed. Go to the red rectangle code:

                                        //red rectangle
                                        newShape ( );
                                        x = 550;
                                        y = 400;
                                        width = 200;
                                        height = 100;
                                        g2.setPaint (red);
                                        g2.fillRect (x, y, width, height);

    Change the x and y variables to be:

                                        x = xBwdLine (550, 10);
                                        y = yBwdLine (400, 10);

    You can experiment with the starting coordinates and the speeds. Save, compile and run your program.


  7. Making a Shape Bounce
  8. There are also the xBounce and yBounce methods, these methods will make the shape move back and forth in the x or y direction. These methods have two parameters. The first is a measure of how far the shape should move back and forth and the second is how fast it should move. Both of these are integers. You are going to use the xBounce method to make the magenta oval move back and forth along the y-direction. Go to the oval's code:

                                       //magenta oval
                                        newShape ( );
                                        x = 300;
                                        y = 200;
                                        width = 120;
                                        height = 75;
                                        g2.setPaint (magenta);
                                        g2.drawOval (x, y, width, height);

    You want the x-coordinate to move forward in a line and the y-coordinate to move up and down. Change the x and y variables to:

                                        x = xFwdLine(300, 5);
                                        y = yBounce(20, 5);

    Save, compile and run your program. You should try changing the parameters in this method.


  9. Making a Shape Spin
  10. There are also methods that will rotate the shapes, without affecting the x or y coordinates. You are going to make the green and blue square spin around itself, using the spin method. This method has one integer parameter: the speed the shape should rotate at. To use this method, you would type
    spin(speed). Go to the square's code:

                                        //green & blue square
                                        newShape ( );
                                        x = 120;
                                        y = 350;
                                        width = 100;
                                        height = 100;
                                        g2.setPaint ( Fade(green, blue) );
                                        g2.fillRect (x, y, width, height);

    Place your cursor at the end of the height = 100; line and press Enter. On this new line, type:

                                        spin (10);

    You can change the speed if you want. Your code should now look like:

                                        //green & blue square
                                        newShape ( );
                                        x = 120;
                                        y = 350;
                                        width = 100;
                                        height = 100;
                                        spin (10);
                                        g2.setPaint ( Fade(green, blue) );
                                        g2.fillRect (x, y, width, height);

    Save, compile and run your program.

    Note: To make a line spin, you should use the method spinLine. To use this method you would type spinLine(speed).


  11. Moving in a Circle
  12. Through the use of the circle method, you can make your shapes rotate in a circle about a specified point. To use this method you would type circle(speed, x, y), where the first parameter is the speed the object should rotate at, and the second and third are the x and y coordinates it should rotate about. You are going to make the orange line rotate in a circle. Go to the line's code:

                                        //orange line
                                        newShape ( );
                                        x1 = 500;
                                        y1 = 200;
                                        x2 = 700;
                                        y2 = 10;
                                        g2.setPaint (orange);
                                        g2.drawLine (x1, y1, x2, y2);

    Just like what you did in the last step, place your mouse at the end of the y2 = 10; line and press Enter. On the new line type:

                                        circle (10, 450, 250);

    Now the line will rotate about point the (450, 250). Save, compile and run your program. You can experiment with changing the speed and the rotation point variables.


  13. A Little More Creativity
  14. Play with the different animation methods on the extra shapes you created in Part I. Try varying their parameters and combining the rotation methods with the coordinate ones.


    Here is a summary of the animation methods available to you:

    Coordinate Methods:
    xFwdLine (int start, int speed)
    Moves the x-coordinate forward (to the right) with the specified speed, from the specified starting point.
    xBwdLine (int start, int speed)
    Moves the x-coordinate backward (to the left) with the specified speed, from the specified starting point.
     
    yFwdLine (int start, int speed)
    Moves the y-coordinate forward (down) with the specified speed, from the specified starting point.
     
     
    yBwdLine (int start, int speed)

    Moves the y-coordinate backward (up) with the specified speed, from the specified starting point.

    xBounce (int dist, int speed)
    Moves the x-coordinate back and forth the specified distance, at the specified speed.

    yBounce (int dist, int speed)
    Moves the y-coordinate up and down the specified distance, at the specified speed.

    Rotation Methods:
    spin (int speed)
    Makes a shape rotate about itself, at the specified speed.

    spinLine (int speed)
    Makes a line rotate about itself, at the specified speed.

    circle (int speed, int x, int y)
    Makes a shape rotate in a circle about the specified point (x,y), at the specified speed.

 


Reference Links

  1. The Java API has a listing of all the pre-packaged Java classes (Graphics, Graphics2D and Color are relevant for this lab), descriptions of their methods and how to use them. There is also a handy alphabetical index.
    http://java.sun.com/j2se/1.3/docs/api/index.html

  2. The Java Sun site has tutorials for using both the Graphics and Graphics2D classes, as well as most Java topics.
  3. Graphics Class
    http://java.sun.com/docs/books/tutorial/uiswing/14painting/index.html

    Graphics2D Class
    http://java.sun.com/docs/books/tutorial/2d/index.html

    List of all Java Tutorials
    http://java.sun.com/docs/books/tutorial/index.html