Updated: 2005/10/22
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.
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.
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 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.
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.
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:
The Colour Class
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.
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.
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.
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.
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.
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).
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.
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.
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:
- Experiment with the size and placement of your shapes and try adding some new ones.
- Try to create graphics that have meanings.
- For example, you can create a stick-man using a combination of circles and lines.
- Or, you could try something more abstract. Click here for some examples.
As a minimum, your program must display these requirements:
- One of each of the following shapes:
- circle or oval
- square or rectangle
- line
- At least one of the shapes must be painted with a thick line.
- At least one of the shapes must have 2-color gradient paint.
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.
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.
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.
- One of each of the following shapes:
- circle or oval
- square or rectangle
- line
- At least one of the shapes must be painted with a thick line.
- At least one of the shapes must have 2-color gradient paint.
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!)
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 (;)).
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.
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.
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.
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)
.
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.
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:
Moves the y-coordinate backward (up) with the specified speed, from the specified starting point.
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
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