Fcps Java Packets: Unit Two - Graphics and Animation
Fcps Java Packets: Unit Two - Graphics and Animation
Fcps Java Packets: Unit Two - Graphics and Animation
Unit2
FCPS
Java
Packets
Unit Two – Graphics and Animation
August 2008
Two-1
Java
Unit2
Contributing Authors
The author is grateful for additional contributions from Marion Billington, Charles Brewer, Margie Cross, Cathy Eagen,
Philip Ero, Anne Little, John Mitchell, John Myers, Steve Rose, Ankur Shah, John Totten, and Greg W. Price.
License Information
This work is licensed under the Creative Commons Attribution-Noncommercial-No Derivative Works 2.5 License. To
view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/2.5/ or send a letter to Creative Commons,
543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.
* Attribution. You must attribute the work in the manner specified by the author or licensor.
* Noncommercial. You may not use this work for commercial purposes.
* No Derivative Works. You may not alter, transform, or build upon this work.
* For any reuse or distribution, you must make clear to others the license terms of this work.
* Any of these conditions can be waived if you get permission from the copyright holder.
You are free to alter and distribute these materials within your educational institution provided that appropriate credit is
given and that the nature of your changes is clearly indicated. As stipulated above, you may not distribute altered
versions of these materials to any other institution. If you have any questions about this agreement please e-mail
smtorbert@fcps.edu
Two-2
Java
Unit2
Two-3
Java
Unit2
Discussion
Panels and Frames
Robot worlds in JKarel were depicted in graphics windows. Graphics windows are created as instances of the
class JFrame. A frame is a window with a border and a title bar. Content is made visible on frames using panels.
Whatever you want the user to see is placed on a panel and that panel is placed on a frame.
The class hierarchies from Sun’s Java API are shown below. Fortunately, because of object-oriented
programming, you don't have to know the details of each class! Each of your driver programs will create a frame.
In your graphics programs, each frame object will instantiate a panel object. The panel class that you make will
inherit lots of functionality from the hierarchy. As you know, inheritance uses the keyword “extends”:
Notice that Panel00 isa JPanel isa JComponent isa Container isa Component isa Object.
Note that a frame is able to hold panels because each frame is also a container. Eventually we will use a panel’s
container ability to hold sub-panels.
(0,200)
(0,225)
The coordinate system treats the upper-left corner of the panel as (0, 0). As you move horizontally to the right the
x-values increase—this should be exactly as you are accustomed. As you move vertically down the y-values
increase—this should be exactly backwards from what you are accustomed.
The reason the origin is placed at the upper-left corner rather than the lower-left corner is so that the origin
remains fixed even when the user resizes the frame. Users typically manipulate the bottom-right corner in order
to resize a frame.
Two-4
Java
Unit2
Lab00
Hello World
Objective
The difference between a driver and a resource.
Background
In our graphics programs we have two files, a driver class and a resource class. The driver sets up the JFrame and
instantiates the panel. The panel is the resource where all the action happens.
Graphics programs have two (or more) files. Make sure you save both files in the same folder, Unit2\Lab00. You
may have to ask your teacher how to get the students' shells for Unit2.
Specification
Create both Unit2\Lab00\Driver00.java and Unit2\Lab00\Panel00.java. Enter the source code shown above, then
compile and run the program. Note that the panel is just a resource. Do not run the panel. Run the driver.
Experiment by changing the values shown.
Test Data
Go to www.tjhsst.edu/compsci.
Two-5
Java
Unit2
Lab00modify
Subway Graffiti
Objective
To apply your understanding of font, color, and drawString() commands.
Background
In Lab00, you created a new Color object (it was gold) with the constructor new Color(150, 150, 0).
Indeed, you can create any color by specifying the red-green-blue values (integers between 0 and 255). To make
it a bit easier, the Color class also predefines thirteen colors: black, blue, cyan, darkGray, gray, green, lightGray,
magenta, orange, pink, red, white, and yellow. To set the color to red: g.setColor(Color.red);
After you set a color, everything is drawn or written in that color until you change it.
There are three different styles of font in the Font class: plain, bold, and italic. To set a plain font:
g.setFont(new Font("Serif", Font.PLAIN, 8));
drawString() takes three arguments, a string and an (x, y) pair of coordinates, which specify the position of
the baseline, as shown below. For any font, the height of the big rectangle is called the height, the height of the
middle rectangle is called the ascent, the height of the lower rectangle is called the descent, and the height of the
upper rectangle is called the leading.
(x, y)
yẼS baseline
Assignment
Create Unit2\Lab00\Driver00.java. Modify the file as needed.
Two-6
Java
Unit2
Exercises
Lab00
Answer these questions using Sun’s Java API. The API (Application Programming Interface) is a document
which lists and describes all you need to know about certain classes. The Java API is available on-line through
any web browser. Ask your teacher how to access the API.
1) What is a “constructor”?
7) What is a “superclass”?
9) What is a “subclass”?
Two-7
Java
Unit2
Discussion
Drawing Shapes
Many of the drawing methods take four arguments, (x +100, 20)
(x, y, width, length). The (x, y) establishes the (x, y)
absolute upper-left corner of the shape, and (width,
length) are relative from that. The diagram shows
example fillOval(20,20,100,50)
(x, y+50)
The following shapes take four arguments. Note the filled form of the
commands to produce filled rectangles and ovals. Make sure you know
how the numbers work!
Rectangle g.drawRect(50, 50, 400, 75);
Square g.fillRect(500, 50, 200, 200);
Ellipse g.drawOval(200, 200, 20, 80);
Circle g.fillOval(500, 300, 100, 100);
Point g.drawRect(400, 600, 0, 0);
In these shapes, the pairs of arguments refer to (x, y) coordinates that are
endpoints of the line segments. All four coordinates are absolute.
Note that the third argument to polygon and polyline is the number of points that make up the polygon or
polyline. This value will be equal to the length of each array xPoints and yPoints. The difference in these
two commands is that a polygon automatically connects the last point back to the first; a polyline does not. Be
careful! The order of the points for a polygon makes a difference. For instance:
P0 P1 P0 P1
P3 P3 P2
P2
Two-8
Java
Unit2
Lab01
Welcome Home
Objective
To understand graphics commands for drawing shapes.
Background
If you supply the correct arguments, the following code will draw the house shown below:
//draw the triangle, which needs three points: (75, 200) and
int xPoints[] = {___, ___, ___}; // (175, 150) and
int yPoints[] = {___, ___, ___}; // (275, 200)
g.drawPolygon(xPoints, yPoints, 3); //draw the black roof
g.setColor(Color.yellow);
g.fillOval(___, ___, ___, ___); //draw the yellow sun
g.setColor(Color.white);
g.drawString(__________________, ____, _____); //say "Welcome Home"
Assignment
Create a new Java driver and panel in folder Unit2\Lab01. Reproduce the house below.
Sample Run
(0,0)
Welcome Home
g.fillOval(300, 75, 50, 50);
(75, 200)
(175, 150)
(275, 200)
g.drawRect(100, 200, 150, 150);
Two-9
Java
Unit2
Discussion
Loops in graphics
To draw a series of lines, from (0, 25) to (0, 200), (10, 25) to (10, 200), (20, 25) to (20, 200), …, (400, 25) to
(400, 200), use the code shown below. Note that the y-values of the endpoints are always 25 and 200. The x-
values of the endpoints are always the same number (for each line), and this number increases by 10 with each
iteration of the loop.
This loop produces x values of 0, 10, 20, 30, …, 400. These two lines of code
draw the forty-one lines you see on the panel. It is as if we had written out forty-
one different drawLine commands, but it only took us two lines of code. Oh, the
power of a for-loop.
Assignment
Add a picket fence in front of your house in Lab 01. When you finish, write the for-loop for your picket fence
here:
Add repeated ovals for clouds. You may experiment and find ones that you like. When you finish, write the for-
loop for your clouds here:
Then write the for-loops that produce the clouds shown below.
Exercises
Lab01
Using the Graphics object g, create the following shapes:
1) Draw a rectangle whose top-left corner is at position 50, 75 and whose width is 100 and height is 200.
Two-10
Java
Unit2
2) Draw a square whose top-left corner is at position 200, 150 and whose sides have a length of 100.
4) Draw a circle at position 50, 100 (position of top-left corner of imaginary rectangle in which the circle will be
placed) with a width and height of 60.
50, 100
5) Now draw that same circle except use 50, 100 as its center point.
6) Draw an ellipse at position 100, 100 (position of top-left corner of imaginary rectangle in which the ellipse
will be placed) with a width of 80 and height 30.
100, 100
7) Now draw that same ellipse except use 100, 100 as its center point.
8) Using your knowledge of the drawRect and drawLine methods, create the following figure whose top-left
corner is at 20, 20 and whose width is 100 and height is 80. (Hint: First write the commands to draw the
rectangle, then write the commands to draw the four lines inside the rectangle.) It might help to label the
beginning and ending points of each of the 4 cross lines.
Two-11
Java
Unit2
Lab02
Our Fearless Leader
Objective
drawImage() and fillOval().
Background
Java uses an ImageIcon object to store a jpg, jpeg, gif, or png file:
For this to work there must be an image file named "tj.jpg" in your Unit2\Lab02 folder. This image can be
displayed with its upper-left corner at (50, 50) by using one of the commands:
The arguments 25 and 75 scale the image. The argument null is a place-holder for a certain object which
drawImage() requires, but we don't care to supply. In this case, "null" means about the same as “empty.”
Note how different types of objects work together in order to make the image appear on the screen:
The fillOval() method can be used to draw circles. The method requires four arguments. The first two arguments
specify the upper-left corner of the rectangle (or square) enclosing the oval (or circle). They do not specify the
center of the circle. The last two arguments specify the width and height of the enclosing square, also known as
the circle’s diameter. The last two arguments do not specify the radius of the circle. On the other hand, we often
want to draw circles from the center with a certain radius. For a circle with center at (x, y) and radius r, use:
g.fillOval(x – r, y – r, 2 * r, 2 * r);
Be careful! The compiler will not translate 2r. You must write 2 * r.
If you can make the x change, say in a for-loop, you can draw a horizontal
row of repeated circles for a frame effect. How do you draw a vertical row
of circles?
Specification
Look at Unit 2, Lab02 at www.tjhsst.edu/compsci. Duplicate this picture:
Create filename Unit2\Lab02\Driver02.java. Make sure to add a panel object of type Panel02.
Create filename Unit2\Lab02\Panel02.java. Use graphics commands to draw a framed picture of your school’s
namesake, principal, or inspirational leader. Estimate all distances by trial-and-error.
Two-12
Java
Unit2
Exercises
Lab02
Using the Graphics object g, create the following shapes:
1) Use a for-loop to create the following image. Each line is 50 pixels long and 5 pixels apart. The top of the
first line is at 80, 50.
2) Use a for-loop to create the following image. Each filled circle is 20 pixels across, and the first circle on the
left has an upper-left corner position of 100, 0.
3) Use a for-loop to create the following image. Each filled circle is 20 pixels across, and the upper-most circle
has an upper-left corner position of 100, 100.
400, 400
Two-13
Java
Unit2
Discussion
Buffering an image
Up to now, we drew graphics directly on the panel by sending commands to the g object in paintComponent().
Starting with Lab03 we will draw the image in an off-screen buffer, or temporary storage area, and then “paste”
the complete image on the screen once at the end. Drawing to a buffer is much faster than drawing to the screen.
When we start animation, with lots of drawing commands, using the buffer eliminates images that flicker.
To store such a buffered image object we declare a private field myImage (line 10). We instantiate the
BufferedImage object in the Panel's constructor (line 14). That BufferedImage object has a Graphics object
associated with it (line 15). After that (line 16 and onwards), we send the familiar drawing, color, font, and
drawString() commands to the buffered Graphics object.
6 import java.awt.image.BufferedImage;
7 public class Panel03 extends JPanel
8 {
9 private final int N = 400;
10 private BufferedImage myImage;
12 public Panel03()
13 {
14 myImage = new BufferedImage(N, N, BufferedImage.TYPE_INT_RGB);
15 Graphics buffer = myImage.getGraphics();
16 buffer.setColor(Color.blue);
17 buffer.fillRect(0, 0, N, N);
All the graphics commands work exactly as you would expect them to. The only difference is that you are
sending messages to the buffered object. In order to actually see what you've drawn, you must “paste” the
buffered image onto the panel, using one command in paintComponent():
The methods getWidth and getHeight return the current width and height of the panel. These values may
change during runtime if the user resizes the frame. When you resize, the image will change to fill up the panel.
There is a shell for Lab03 that has this off-screen buffer already set up for you. Don’t change it!
Two-14
Java
Unit2
Lab03
Webbing and Sunshine
Objective
Calculating end-points and using drawLine().
Background
The first task is to draw webs at the corners. This for-loop draws a web in the
upper-right corner of the N x N image:
Notice that 51 lines will be drawn. drawLine() takes two pairs of coordinates, the end points of each line. One
endpoint of each line needs to move from left to right across the top of the image while the other endpoint needs
to move from top to bottom down the right side of the image. If we can make x increase, then (x, 0) will slide the
top endpoint over. At the same time, an increasing y will slide (N, y) down. We can make x and y increase in a
for-loop, for as k increases from 0 to 50, the expression N * k / 50 increases from 0 to N in 50 equal increments.
Thus, the calculated coordinates (N * k / 50, 0) and (N, N * k / 50) together slide the x-coordinate of the first point
along the top and the y-coordinate of the second point down the right side. (Warning! Due to something called
"integer division," the expression k / 50 * N will evaluate to 0. Make sure to multiply N * k before dividing by
50.) You'll have to figure out how to move the endpoints for the other three corners.
x1, y1
x1, y1
The second task is to draw the rays of the sun. The center is at (x, y) but each of the
other endpoints must be calculated. From geometry, we know that in any right
triangle the sine of an angle is the ratio of its opposite side to its hypotenuse and the x1, y1
cosine of an angle is the ratio of its adjacent side to its hypotenuse. This means that
if we know the angle and the length of the hypotenuse, we can determine the lengths θ x1, y1
of the opposite and adjacent sides, which are the coordinates (x1, y1). The angle θ x, y
changes from 0 to 360 in equal increments, depending on how many rays we want.
We'll use a for-loop to change the angle, of course. Inside the for-loop we will
calculate the (x1, y1) coordinates and draw the line.
It happens that Java's Math.cos() and Math.sin() methods require radian arguments.
Since most people prefer to think in degrees, we multiply degree measures by
Math.PI / 180. Also, these trigonometry methods return decimal values, so we need
to cast the coordinates to integers using (int). For example:
Specification
Filename Unit2\Lab03\Driver03.java. Make an appropriate driver, then compile and run.
Filename Unit2\Lab03\Panel03.java (load). Complete the definition of the constructor to draw the full, four-
cornered webbing and a sun with rays. Draw 12 rays at first, but make it easy to draw any number of rays.
Extension
Change all constants into variables. Prompt the user to enter N, k, the number of lines, and the number of rays.
Two-15
Java
Unit2
1) A field in Java is a variable created and used by a class. How many fields are in the Math class?____
2) What two numbers are stored in the fields of the Math class?
3) The Math class fields are marked public static final double. Explain what each word means.
public
static
final
double
4) Explain why it makes sense that π and e are public static final double in Java.
5) How many constructors does the Math class define? ______Why does that make sense?
7) How many void methods does the Math class define? ____
9) How many no-argument methods does the Math class define? ________ Name them ________________
11) How many direct known subclasses does Number have? _______
12) How many interfaces does Integer implement? _______ Name them ______________________________
Two-16
Java
Unit2
Lab04
Buckets
10 public class BucketPanel extends JPanel
Objective 11 {
Class method vs. instance method 12 public BucketPanel()
13 {
Background 14 Timer t = new Timer(10, new Listener());
15 t.start();
As usual, the driver instantiates a subclass of
16 }
JPanel in a JFrame. Then BucketPanel manages 17 public void paintComponent(Graphics g)
the animation. 18 {
1.edu.fcps.Bucket has its own 19 g.drawImage(Bucket.getImage(), 0, 0,
BufferedImage, which stores all the getWidth(), getHeight(), null);
20 }
g.setColor() and g.fillRect() commands, as 21 private class Listener implements ActionListener
well as little white digits. 22 {
2.Line 19 paints the picture on the screen, 23 public void actionPerformed(ActionEvent e)
as usual. 24 {
25 repaint();
3.On line 14, the BucketPanel constructor 26 }
also instantiates and starts a Timer. 27 }
4.When the Timer reaches 10, it instantiates a Listener, which does one thing, namely, it repaints the screen
(line 25). Since 10 milliseconds is a short time, the water appears to move.
5 import javax.swing.*;
The Bucket Class gives you the tools to program a 6 import edu.fcps.Bucket;
solution for the following logic problem: Given two 7 public class Driver04
buckets, a 3-gallon bucket and a 5-gallon bucket, how 8 {
9 public static void main(String args[])
can you measure out exactly 4 gallons? The algorithm 10 {
to implement is: 11 JFrame frame = new JFrame("Buckets");
1. Fill the five-gallon bucket. 12 frame.setSize(600, 400);
13 frame.setLocation(100, 100);
2. Pour from five into three until three is full.
14 frame.setDefaultCloseOperation(
3. Empty the three-gallon bucket. JFrame.EXIT_ON_CLOSE);
15 frame.setContentPane(new BucketPanel());
4. Pour from five into three until five is empty. 16 frame.setVisible(true);
5. Fill the five-gallon bucket. 17 Bucket.setSpeed(5);
18 Bucket.useTotal(false);
6. Pour from five into three until three is full. 19
7. Done! The amount left in five is exactly 4. 20 Bucket five = new Bucket(5);
21 Bucket three = new Bucket(3);
Clearly, a bucket object should “know” how to fill, 22 // implement the algorithm here
empty, and pour. Look at the API for details. 23 }
24 }
Assignment: Write Driver04 to implement the algorithm to get exactly 4 gallons. Don’t change BucketPanel!
Until now, each object of a class had its own copy of each method in that class. Each method was duplicated and
belonged to each individual object. However, sometimes it is convenient to make methods belong, not to each
object, but to the class, as class methods. Because class methods are not duplicated, a programmer thinks of them
as “static,” and Java uses the keyword static to indicate them. Look at the Bucket API and notice that about half
the methods are static and half are not. Let’s talk about:
public static void setSpeed()
public static Boolean useTotal()
public void pourInto()
The keyword static means that the objects don’t get their own instance (copy) of these methods. In other words,
there is only one copy of useTotal() and of setSpeed(), but lots of instances of pourInto(). It
makes sense that speed and total volume belong to the class, not to any one object. The dot-notation in line 17
indicates that the Bucket class itself “knows” how to setSpeed(). Static methods add powers to the class, but not
to the objects of the class.
Two-17
Java
Unit2
Lab04
Buckets, Part II
Objective
Class field vs. instance field
Background
The keyword static means there will be only one copy no matter how many objects are created. static can
apply not only to methods but also to fields. Part of the code in the Bucket class looks like:
class Bucket
public class Bucket
{ totalWater 10
private static int totalWater;
private int myWater;
(object) three
...
myWater 3
}
In the code for Driver04, you called the class 5 import edu.fcps.Bucket;
method Bucket.useTotal(false). The 6 import javax.swing.*;
effect of this mystery command was not to use 7 public class Driver04a
the static field totalWater. Instead each 8 {
bucket object kept track of its own volume of 9 public static void main(String args[])
10 {
water, as is usual with objects. In that program, 11 JFrame frame = new JFrame("Buckets");
when either bucket held a certain number of 12 frame.setSize(600, 400);
gallons, it turned that number from white to red. 13 frame.setLocation(100, 100);
Run it again and notice when the little white 14 frame.setDefaultCloseOperation(
numbers turn red. JFrame.EXIT_ON_CLOSE);
15 frame.setContentPane(new BucketPanel());
In contrast, the code for Driver04a has a call in 16 frame.setVisible(true);
line 18 to Bucket.useTotal(true). The 17 Bucket.setSpeed(5);
18 Bucket.useTotal(true);
effect of this is to use the static field 19 Bucket five = new Bucket(5);
totalWater, which will keep track of the total 20 Bucket three = new Bucket(3);
volume of water in all the buckets. In this case, 21 // implement the algorithm here
when both buckets hold a certain number of 22
gallons, it turns that number from white to red.
Assignments
Lab04a: Modify Driver04. This time, track the total volume of water. Turn the white numbers to red, showing
that the system can measure out 1, 2, 3, 4, 5, 6, 7, and 8 gallons.
Lab04b: Create a new driver named Driver04b. Make three Bucket objects, of 3, 4, and 5 gallons. Track the
total volume of water by turning the white numbers to red. Show that the system can measure out 1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, and 12 gallons.
Two-18
Java
Unit2
Exercises
Lab04
1) Given two buckets named five and six with capacities of five and six, respectively, produce exactly four
gallons of water.
2) Given two buckets named four and five with capacities of four and five, respectively, produce exactly two
gallons of water.
3g) Each Bucket object has two private fields. How do you change the value of myCapacity?
5) A certain class has the code for methods for public void a() and public static void b().
In the driver, you instantiate three objects from this class. How many copies of a()do you have? _______
How many copies of b() do you have? ____
Two-19
Java
Unit2
Lab05
Bugs
Objective
To use a resource class to solve a problem.
Background
In object-oriented programming, objects have
encapsulated data and methods. The idea is that the details
of the implementation are hidden from you, the user. The
API lists the class’s fields, constructors, and methods.
What does a bug know? Bugs know where they are. Each
bug stores its position as two integers in its private fields.
These x- and y-coordinates are the only data stored by a
bug object.
What can bugs do? Bugs are able to tell you where they
are. They will report their position through their two
public int methods getX() and getY().
What else can bugs do? A bug can also walk towards another bug. You have to tell the bug which other bug to
walk towards and also what percentage of the total distance to travel. Thus, the public void method
walkTowards() requires two arguments, one bug and one decimal number representing the percentage of the
total distance to travel.
Are bugs able to draw lines? Look at the API. The API says nothing
about drawing lines. How will you draw lines?
Specification
Filename Unit2\Lab05\Driver05.java (load). Create four bugs located
in the four corners of your image. So long as any two bugs are not
standing at the same position, have each bug walk ten percent of the
way towards its clockwise neighbor. At each iteration of this process,
draw four lines on the image showing the distance remaining between
each pair of neighbors.
Test Data
Go to www.tjhsst.edu/compsci.
Two-20
Java
Unit2
Exercises
Lab05
On the left is the source code for the resource class called Bug. On the right is an object diagram.
1. Mark the private fields “F”, the constructor “C”, two accessor methods “A”, and two instance methods “I”.
2. Write the code to instantiate a Bug object named “lady” along the top of the pane, 37 pixels to the right of the
upper-left corner.
3. Although myX is private (encapsulated), getX() is public. What does getX() allow the programmer to do?
4. Tell a bug named “june” to store her x position in the variable temp.
5. Tell a bug named pete to walk halfway towards a bug named mary.
6. Look at the code for walkTowards(). Explain how the new (x, y) position is calculated.
Two-21
Java
Unit2
Discussion
The Turtle class
In the early 1970s MIT introduced a turtle to the LOGO
language. Turtles are similar to Bugs and Robots, but are
much more complex and powerful.
Two-22
Java
Unit2
Discussion
Classes, Abstract Classes, and Objects
When you first see a new class, the question you should always ask is: what can this class do to itself?
The Turtle class has both static and dynamic fields and methods. The static fields and methods stay with the class
and the dynamic fields and methods are duplicated in each object.
setSpeed()
setCrawl()
The Turtle class is abstract because at least one
method, in this case drawShape(), is abstract..
isa
Two-23
Java
Unit2
Lab06
Square Turtles
Objective
To understand turtles and implement an abstract method. Turtle
Background
Look at the API for SquareTurtle: Notice these important points:
1. SquareTurtle extends Turtle. This creates a hierarchy where Turtle is the super-class SquareTurtle
and SquareTurtle is the sub-class. SquareTurtle inherits everything Turtle knows.
2. The SquareTurtle class has four constructors. The default constructor gives you one kind of SquareTurtle.
The other constructors allow you to instantiate SquareTurtles with different values.
left: __________________________
center: __________________________
right: _______________________________
3. What private data does a SquareTurtle store? ______________
4. What set method allows you to change a SquareTurtle’s private data?___________ What other way can you
use to set an object's private data? ________________________
5. SquareTurtle has one instance method, drawShape(). Since drawShape() was abstract in Turtle, SquareTurtle
must provide a definition drawShape(). Overriding a method is when a sub-class provides a definition for a
super-class method. The overridden method is the one that gets used by SquareTurtle objects.
Specification
Filename Unit2\Lab06\SquareTurtle.java (load). Complete the SquareTurtle class by implementing the
drawShape() method. Note that this is required because drawShape() is tagged abstract in Turtle.
Filename Unit2\Lab06\Driver06.java (load). Create four turtles such that you use all four of the square turtle’s
constructors. Draw squares of various colors, sizes, and thickness. Change one of your turtle’s sizes in the
program so that one turtle ends up drawing two squares with different sizes.
Test Data
Go to www.tjhsst.edu/compsci.
Extensions
1. Draw the square using a for-loop.
2. Run the program with crawl turned off. What happens to the speed of the program?
Two-24
Java
Unit2
Exercises
Lab06
Note the three special-case triangles shown below. Use Math.sqrt(3.0) for the square root of three.
x
x x x x
2x
2x
x
3x
Complete the drawShape method for each of the three Turtle classes shown below.
1) EquilateralTurtle 2) ThirtySixtyNinetyTurtle
public void drawShape() public void drawShape()
{ {
} }
}
Lab07
Two-25
Java
Unit2
Polygon Turtles
Objective
To solve a generic problem with turtles.
Background
What are the private fields in a
Polygon Turtle?
___________ and
___________
What modifier methods will
probably be in Polygon Turtle?
_________________
and ______________
where does odysseus start? ___________________ what path will odysseus follow?
Specification
Copy the TurtlePanel.class file from Unit2\Lab06 to Unit2\Lab07 noting that
you do not need the source code so you do not have to copy the
TurtlePanel.java file. Also copy the two class files for the inner class and the
anonymous inner class. Both of these other files will begin with TurtlePanel
and a dollar sign ($).
Two-26
Java
Unit2
Exercises
Lab07
1) Complete a Bug’s getX() method below:
public int getX()
{
3) In Lab07, you made different polygons by changing the number of sides through setSides(). It would be nice
to set the number of sides through an argument to drawShape(). For example, drawShape(4) would draw a square.
Overload the drawShape() method so that it takes one integer argument, which sets mySides and then draws the
appropriate polygon.
4) Write the code to produce this shape. It should use the overloaded
drawShape(int s) from above. Use a for-loop to set the number of
sides.
5) Why does an object-oriented program go to all the trouble to create private data, and then create get and set
methods? What advantage is there to having private data and public get and set methods?
Two-27
Java
Unit2
Discussion
Access Modifiers
The two access modifiers we will use in this course are public and private. Every program outside the class
can use the public methods. Only methods inside the class can use the private methods. As a matter of
convention all data fields are private.
The driver program, which acts as a client of the FlowerTurtle server, FlowerTurtle
setColor()
cannot directly access the private values mySize and myColor. (The mySize
prefix my is also a convention, meant to convey the fact that each myColor
drawShape()
object knows its own size and its own color.) The driver is able to
change mySize and myColor only through public methods. The two drawPetals()
“set” methods, also called modifiers or mutators, allow the
user/client/driver to change the initial values.
drawStem()
public class Driver08
{
public static void main(String[] args)
{
FlowerTurtle lisa = new FlowerTurtle(300.0, 50.0, Color.red);
lisa.setSize(25.0); //modifier method
lisa.setColor(Color.blue); //modifier method
lisa.drawShape(); //public instance method
}
}
Most methods we write will be tagged public so that those methods are accessible from other classes. However,
in FlowerTurtle, the two helper methods will be tagged private and are only to be used by a FlowerTurtle. A
FlowerTurtle’s drawShape() method draws a pretty flower. “Drawing a flower” is broken into two parts, to draw
the petals and then to draw the stem. Therefore, the code in drawShape() is as simple as possible:
The actual drawing of the flower is taken care of by the two private helper methods drawPetals() and drawStem().
Since Driver08.java is only interested in calling drawShape, in order to draw a complete flower, these two helper
methods do not need to be public.
Two-28
Java
Unit2
Lab08
Flower Turtles
Objective
To tiptoe through the tulips.
setSize()
Background
One other access issue has to do with overridden methods. Once a method FlowerTurtle
setColor()
has been overridden, the original superclass method cannot be invoked. mySize
Usually, this overriding is exactly what we want. Here is an example myColor
drawShape()
where overriding doesn't help us:
drawPetals()
public class Driver08
{
public static void main(String[] args) drawStem()
{
FlowerTurtle lisa = new FlowerTurtle(300.0, 50.0, Color.red);
lisa.setSize(25.0); //calls lisa's setSize()
lisa.setColor(Color.blue); //calls lisa's setColor()
lisa.drawShape();
}
}
Lisa's setSize() works as intended. However, the author wrote setColor() to simply store a value in myColor. It is
Turtle’s setColor() that actually sets the color of lisa's pen color. The author really should have given a different
name to lisa's setColor() method.
However, all is not lost. The superclass's setColor() can be called from within the definition of the class that
overrode it. So from inside FlowerTurtle, Turtle’s setColor() can be invoked. For example:
Specification
Copy the three TurtlePanel class files into Unit2\Lab08.
Test Data
Go to www.tjhsst.edu/compsci.
Two-29
Java
Unit2
Discussion
References
Here is a class method that requires an argument of type Turtle.
drawShape() is specified in the Turtle class. But what actually happens when twisties() executes? First, it
chooses a random turn and a random direction. Then drawShape() depends on the type of the object that is
actually passed. Recall that smidge is a reference to our turtle object. When smidge is passed to the method
twisties(), only the reference is copied. No new turtle object is created by passing a turtle as an argument to a
method. Both the reference to smidge in main and the reference to arg in twisties() point to the same object.
The actual object, of course, is of type TwistyTurtle. Thus, arg is a reference of type Turtle that points to an
object that is a sub-class of Turtle. The superclass reference is pointing to a subclass object, i.e, we have
polymorphism. The computer waits until runtime to decide which drawShape to execute. At that point, the actual
type of the object that arg points to is known. This mechanism, which produces the polymorphic behavior, is
called dynamic binding or late binding.
Turtle
In this case, Turtle happens to be an abstract class and drawShape() is an abstract method. Both are, in some
sense, empty and/or imaginary, but that doesn't matter. It doesn't matter because the concrete subclasses do have
code for drawShape(). As long as the Turtle reference named arg points to an object of one of Turtle’s sub-
classes, drawShape() will know what to do.
Two-30
Java
Unit2
Lab09
Twisty Turtles
Objective
To draw a pretty picture with a turtle.
Background
TwistyTurtles extend Turtle. TwistyTurtles have no new private fields.
They have one constructor which is a three-arg constructor for location
and heading (use super). The constructor also sets the pen color (use
super). TwistyTurtles implement only one method, drawShape(), which
has one loop. You may use either a for-loop or a while-loop.
You should experiment with your own values for the length of the side, the
increment, and the angle.
Specification
Copy the three TurtlePanel class files into Unit2\Lab09.
Test Data
Go to www.tjhsst.edu/compsci.
Extension:
Using the class method twisties(), draw a square, an octagon, a flower, and a twisty. Explain how this is an
example of polymorphism.
Extension 2:
Have your original TwistyTurtle class implement the Runnable interface (Unit1, Lab14). All run() will do is
call drawShape(). In your driver create three twisty turtle objects each with their own thread. Start the threads
and watch your turtles twist in parallel.
Two-31
Java
Unit2
Lab10
Polka Dots
Objective
To set up a bufferedImage and a timer. The Polkadot class.
Background
Lines 4-7: we need to 4 import javax.swing.*;
import many packages. 5 import java.awt.*;
6 import java.awt.event.*;
7 import java.awt.image.*;
This class "isa" JPanel. 8 public class PolkaDotPanel extends JPanel
9 {
10 //constants
Lines 11 & 12: Why are 11 private static final int FRAME = 400;
these constants both 12 private static final Color BACKGROUND = new Color(204, 204, 204);
static and final? 13 //fields
14 private BufferedImage myImage;
15 private Graphics myBuffer;
Lines 14-18: six private 16 private Timer t;
17 private Polkadot pd;
fields. Line 17 says we 18 private int xPos, yPos;
will be using a Polkadot 19 public PolkaDotPanel()
object. What is that?! At 20 {
21 myImage = new BufferedImage(FRAME, FRAME, BufferedImage.TYPE_INT_RGB);
this point, we don’t need 22 myBuffer = myImage.getGraphics();
to know! 23 myBuffer.setColor(BACKGROUND);
24 myBuffer.fillRect(0, 0, FRAME, FRAME);
25 pd = new Polkadot();
Lines 19-28: constructor. 26 t = new Timer(1000, new Listener());
We continue to use an 27 t.start();
28 }
off-screen buffer, a timer, 29 public void paintComponent(Graphics g)
and a private Listener to 30 {
31 g.drawImage(myImage, 0, 0, getWidth(), getHeight(), null);
produce motion. All the 32 }
action is in Lines 35-42. 33 private class Listener implements ActionListener
On Line 41, repaint() 34 {
35 public void actionPerformed(ActionEvent e)
calls paintComponent, 36 {
which actually puts the 37 /**************************
38 your code goes here
image on the screen. 39 **************************/
40 pd.jump(FRAME, FRAME);
Specification 41 pd.draw(myBuffer);
42 repaint();
43 }
44 }
45 }
Test Data
Go to www.tjhsst.edu/compsci.
Extension
Two-32
Java
Unit2
Modify Polkadot (look at the next page) so that it has a myRadius field. You will also need to modify the
constructors. Create a get-method and a set-method for the radius. Make sure that, whenever you change the
value of the radius (diameter), that the value of the diameter (radius) is likewise changed.
Two-33
Java
Unit2
Discussion 5
6
import java.awt.*;
public class Polkadot
Polkadot 7
8
{
private double myX; // x coordinate of center
9 private double myY; // y coordinate of center
What can a polkadot do? What do they know? The 10 private double myDiameter;
11 private Color myColor;
API below is generated from the code at the right. 12 private double myRadius;
14 public Polkadot()
15 {
16 myX = 200;
17 myY = 200;
18 myDiameter = 25;
19 myColor = Color.red;
20 myRadius = myDiameter/2;
21 }
22 public Polkadot(double x, double y,
double d, Color c)
23 {
24 myX = x;
25 myY = y;
26 myDiameter = d;
27 myColor = c;
28 myRadius = d/2;
29 }
31 public double getX()
32 {
33 return myX;
34 }
35 public double getY()
36 {
37 _____________
38 }
39 public double getDiameter()
40 {
41 _____________
42 }
43 public Color getColor()
44 {
45 return myColor;
46 }
47 public double getRadius()
48 {
49 return myRadius;
50 }
52 public void setX(double x)
53 {
54 myX = x;
55 }
56 public void setY(__________)
57 {
58 ______________
59 }
60 public void setColor(Color c)
61 {
62 myColor = c;
63 }
64 public void setDiameter(double d)
65 {
66 myDiameter = d;
67 myRadius = d/2;
68 }
69 public void setRadius(double r)
70 {
71 __________________
72 __________________
73 }
75 public void jump(int rightEdge,int bottomEdge)
76 { //code
80 }
81 public void draw(Graphics myBuffer)
85 { //code
86 }
Two-34
Java
Unit2
Discussion
The Ball class
2 import java.awt.*; What does a ball “know?” What can a ball
3 public class Ball extends Polkadot
4 { do to itself?
5 private double dx;
6 private double dy;
7 // constructors The first thing to notice is that a Ball “isa”
8 public Ball() //default constructor Polkadot. Here is the UML diagram
9 { showing this relationship:
10 super(200, 200, 50, Color.black);
11 dx = Math.random() * 12 - 6; // vertically
12 dy = Math.random() * 12 - 6; // sideways Polkadot
13 }
14 public Ball(double x, double y, double dia, Color c)
15 {
16 super(x, y, dia, c); Ball
17 dx = Math.random()* 12 - 6;
18 dy = Math.random() * 12 - 6; The object-oriented concept of “inheritance”
19 } means that a Ball inherits both fields and
20 //modifier methods
21 public void setdx(double x) methods from Polkadot. The author had to
22 { consider exactly how a ball was like a
23 dx = x; polkadot, and what attributes balls should
24 }
25 public void setdy(double y) share with polkadots.
26 {
27 dy = y;
28 } 1. What four fields do balls inherit from
30 //accessor methods polkadots? __________ ___________
31 public double getdx() __________ __________
32 {
33 return dx;
34 } 2. Balls also share behaviors, or methods,
35 public double getdy()
36 { with Polkadots. What two instance methods
37 return dy; does a Ball inherit from a Polkadot?
38 } _________ _____________
40 //instance methods
41 public void move(double rightEdge, double bottomEdge)
42 { 3. The author also gave Ball new fields.
. . .
50 }
Look at Lines 7 and 8. What are the new
fields in Ball? _________ ___________
4. What do you think these new fields do? (The answer has something to do with how balls are different from
polkadots.)
9. The author also gave Ball one new method. In words, describe what has to happen to make the ball appear to
move slowly horizontally.
10. Write the code to cause a ball object at getX() to move dx horizontally.
Two-35
Java
Unit2
Lab11
Bouncing Pinball
Objective
The Ball class and motion.
Background
Here is the actionPerformed method of the 35 private class Listener implements ActionListener
PinballPanel. Just as in the Polkadot lab, the buffer 36 {
37 public void actionPerformed(ActionEvent e)
is painted gray and then a new image is repainted. 38 {
If the ball moves a little bit, and the timer fires 39 myBuffer.setColor(BACKGROUND);
quickly, the ball appears to roll around the screen. 40 myBuffer.fillRect(0,0,FRAME,FRAME);
41 ball.move(FRAME,FRAME);
Notice we have encapsulated both the movement 42 ball.draw(myBuffer);
and the painting in the Ball class, i.e., Ball objects 43 repaint();
44 }
"know" how to move and to paint themselves. 45 }
How can the Ball know when it hits an edge? First, notice that the Ball does not know the dimensions of the
panel, until it is passed those values in Line 42. Second, the Ball "knows" the coordinates of its center, but it
bounces off an edge according to its radius. The code in Line 44-60 has to account for that.
How do the dx and dy change when a Ball hits, e.g., the right edge? How dy
many edges do you have to worry about? dx
Specification dy
Copy Unit2\Lab10\Polkadot. (Why do you have to copy it, if we don't use it?)
Filename Unit2\Lab11\Ball.java (load). The ball moves sideways and bounces off the right edge (don't change
it!). Use that code as a model to make the Ball move in all directions and bounce off all edges.
Two-36
Java
Unit2
Lab12
Get the Prize
Objective
Using multiple classes with appropriate responsibilities.
Background
Object-oriented programming attempts to distribute appropriate responsibilities to the different classes. Polkadots
should do polkadot stuff, balls should do ball stuff, and panels should organize them. In this lab, panel's
responsibility is also to decide when the moving ball actually hits the polkadot, to count those times, and to
display the count. That is, PrizePanel eventually will have an additional private field to store the number of hits,
a private method called collide and a private method called distance.
Line 58: How do they know they collide? The ball and the polkadot each "know" their x2, y2
own position. If the distance between their centers (recall the distance formula from
algebra) is less than the sum of their respective radii, then they hit.
x1, y1
The distance formula uses both Math.sqrt() and Math.pow(), which return
doubles. The expression to square the difference between x2 and x1 is Math.pow(x2 – x1, 2);
Specification
Copy Polkadot.java and Ball.java from Lab11.
Two-37
Java
Unit2
Lab13--Project
Riddle Me This
Objective
To make your teacher and classmates laugh.
Background
Ever since Lab03, we have pretended that myImage's image was a Graphics type object. In truth, Graphics is
abstract, so the actual object created is a subclass of Graphics. Then when the Java programmers decided to add
more powers to the Graphics class, they chose to extend it. They named the new class Graphics2D, and also kept
it abstract. Look at the API for Graphics2D.
Graphics2D inherits familiar Graphics methods like fillRect(), drawPolyline(), setColor(), and setFont(). It
overrides and overloads the method drawString(). Graphics2D helpfully defines new methods setBackground()
and setStroke(). The methods setStroke() and BasicStroke(), which takes a floating point number as an argument,
can be used to change the thickness of lines like this:
Test Data
Go to www.tjhsst.edu/compsci.
Two-38
Java
Unit2
Lab14
Prize with Bumper
Objective
Designing a class from scratch (mostly).
Background
The panel is just like Lab12, with a moving ball, a jumping prize, and a
counter, but has a rectangular bumper somewhere in the middle of the
screen. The bumper is (of course) an object of the Bumper class. The
author had to ask him/herself a series of questions, including:
5. What instance methods are needed? That is, what should a bumper know how to do?
#1: The author thought about extending Polkadot because both have x and y coordinates. However, since
Bumper does not have a diameter or a radius, it seemed better not to have Bumper extend anything.
#2: Bumpers at a minimum need to know their upper left hand corner, their x-width, and their y-width, because
that is how they are drawn. It might be nice to have different colored bumpers.
#3: The default constructor always places the bumper in the same place. It would be nice to place it in different
places with different sizes. Let’s make two constructors, a no-arg and a 5-arg constructor.
#4: Get-methods are needed to get the x, y, x-width, and y-width. Set-methods might not be needed, unless the
position, size, and color of the bumper need to be changed. If we make Pong, for instance, we will need setY().
#5: A bumper should know how to draw itself, like Polkadot and Ball. If a bumper knows how to jump to a
random location, that would change the game each time we ran it.
Somewhere, we must define how the ball bounces off the bumper. Bouncing off the corners of the bumper
involves “vector algebra.” Luckily for you, the author already wrote and encapsulated all that code in a separate
class. BumperCollision.collide(bumper, ball) is the syntax for calling that magic method.
Specification
Copy Polkadot.java, Ball.java, and Driver12.java from Lab12.
Filename Unit2\Lab14\Bumper.java (load). Complete the design of the class. Create 5 fields, 5 accessor
methods, 5 modifier methods, and 2 constructors. You have 1 instance method to complete. See the next page.
Filename Unit2\Lab14\BumperPanel.java. (load). Instantiate all three objects, than jump them to random
locations.
Test Data
Go to www.tjhsst.edu/compsci
Two-39
Java
Unit2
Two-40
Java
Unit2
Lab15
Karel the Robot
Objective
To solve a really hard problem.
array
Background
We accomplished the appearance of moving balls by quickly
erasing a picture and drawing it again in a slightly new
position. The same appearance of motion can be
[0]
accomplished by cycling through a series of images stored in
an array, if the images are chosen carefully. (This is the way
[1]
animated gifs and sprites work.)
[2]
As the values of the array's index cycles from 0 to 1 to 2 to 3
to 0 to 1 and so on, the image that actually gets displayed
[3]
keeps changing. Each image is just a still shot but the
cycling of images gives the appearance of motion.
This lab will use karel the robot images stored in an array. Karel
can face either east, north, west, or south. Your code will have to
select which image is appropriate. The first, basic assignment is to
make the robot move around the edges of the grid.
array
As with all images, the (xPos, yPos) coordinates of the images [0] [1] [2] [3]
refer to the upper-left hand corner. Unfortunately, the karel
images are not square. That makes proper spacing a bit tricky in
this lab. To get the width and height of the image stored in myArray[0] use the commands:
To actually display the image stored in myArray[0] use the command (last seen in Lab02):
Specification
Filename Unit2\Lab15\KarelPanel.java (load). You will have to
draw the gridlines. Make the robot travel around the grid. Then
make the robot do a dance.
Test Data
Go to www.tjhsst.edu/compsci.
Two-41
Java
Unit2
Lab16
Mouse Input
Objective
To modify the “Get the Prize” lab (Lab 12) to include mouse input.
Background
Background
Not all listeners are ActionListeners
registered with Timers. You can also 16 public PrizePanel()
17 {
register a MouseListener with the JPanel . . .
itself, as on Line 32. 30 t = new Timer(0, new Listener());
31 t.start();
The Listener object on Line 30 is the 32 addMouseListener(new Mouse());
same Listener from Lab12, which 33 }
implements the ActionListener interface, . . .
which controls the motion of the objects. 37 private class Mouse extends MouseAdapter
38 {
The Mouse object on Line 32 could 39 public void mouseClicked( MouseEvent e )
40 {
either implement the MouseListener 41 ball.setX( e.getX() );
interface or extend the MouseAdapter 42 ball.setY( e.getY() );
class. If you implement MouseListener 43 }
you’ll need to define five methods, even 44 }
if you only use one of them. On the
other hand, as a convenience, the MouseAdapter class provides default
(empty) definitions for these methods, so only the methods that you
override need to be defined.
Specification
Copy all files from Lab12. Then modify the mouseClicked method to get three different behaviors from e:
button boolean method desired behaviors
left click <none> moves the polkadot to where you clicked
right click e.isMetaDown() moves the ball to where you clicked
Shift + left click e.isShiftDown() randomly changes the speed and direction of the ball
Test Data
Go to www.tjhsst.edu/compsci.
Extension
Implement an interesting behavior that is allowed by the MouseMotionListener interface. MouseMotionListener
objects are registered with the addMouseMotionListener method.
Two-42
Java
Unit2
Lab17
Keyboard Input
Objective
To modify the “Get the Prize” lab (Lab 12) to include keyboard input.
4 //import statements
Background . . .
Still another Listener is a KeyListener, 9 public class PrizePanel extends JPanel
which can be registered with the JPanel 10 {
itself, as on Lines 32 and 33. . . . //fields
16 public PrizePanel()
The Listener object on Line 30 is the same 17 {
Listener from Lab12, which implements the . . . //code
ActionListener interface, which controls the 30 t = new Timer(0, new Listener());
31 t.start();
motion of the objects.
32 addKeyListener(new Key());
33 setFocusable(true);
The Key object on Line 32 could either 34 }
implement the KeyListener interface or 35 //public instance methods
extend the KeyAdapter class. If you . . .
implement KeyListener you’ll need to define 40 //private listener methods
three methods, even if you only use one of . . .
them. One the other hand, the KeyAdapter 60 private class Key extends KeyAdapter
class provides default (empty) definitions for 61 {
62 public void keyPressed(KeyEvent e)
these methods, so only the methods that you
63 {
actually use need to be defined. 64 if(e.getKeyCode() == KeyEvent.VK_UP)
65 ball.setY( ball.getY()-10 );
Notice that Lines 64, 66, 68, and 70 call 66 if(e.getKeyCode() == KeyEvent.VK_DOWN)
instance methods of a mysterious KeyEvent 67 ball.setY( ball.getY()+10 );
object name “e”. Whenever you press a key, 68 if(e.getKeyCode() == KeyEvent.VK_LEFT)
the e object is passed to the keyPressed 69 ball.setX( ball.getX()-10 );
method. e.getKeyCode() returns the key that 70 if(e.getKeyCode() == KeyEvent.VK_RIGHT)
was pressed. VK_UP is a constant in the 71 ball.setX( ball.getX()+10 );
72 }
KeyEvent class. Therefore, Lines 64 to 71 73 }
move the ball either 10 pixels up, down, left, 74 }
or right.
Specification
Copy all the resource files from Lab12. Modify PrizePanel so that the keys move the polkadot. Do not allow the
keys to move the polkadot outside the boundaries of the panel.
Filename Unit2\Lab17\Driver17.java. (load) Notice that the driver calls the panel's method requestFocus().
Alternatively, you can change the focus by clicking on the panel, which makes the keys work on that panel.
Test Data
Go to www.tjhsst.edu/compsci.
Extensions
1) Modify “Hit the Bumper” Lab14 so that the keys move the wall vertically. Now you can make Pong!
2) Make a two-person Pong game.
3) Modify “Mouse Input” Lab 16 so that it makes use of both mouse and keyboard input.
4) A website that students have found helpful is http://www.faqs.org/docs/javap/index.html
Two-43
Java
Unit2
Discussion
Turtle, from scratch
The shell shown below codes a primitive Turtle class described in Lab06. This primitive turtle does not attempt
to show animation. Why are the img and the colors all static fields? Why are x, y, and theta not static fields?
You'll need a for-loop, obviously. You might find the trig concepts from x, y
Lab03 to be useful. Recall that Java works in radians. Be careful not to set
a pixel that is outside the image.
Feel free to add more constructors and methods to your Turtle class. Some
possible methods to add are turnRight(), back(), penDown(), setColor(), and clear().
Two-44
Java
Unit2
Lab18
Turtle, from scratch
Objective
To solve a problem by first writing a resource class.
Background
public class Lab18 extends JPanel
{
public static void main(String[] args)
{
Turtle t = new Turtle();
t.turnLeft(5);
for(int k=0; k<4; k++)
{
t.forward(100);
t.turnLeft(90);
}
Specification
Filename Unit2\Lab18\Turtle.java. Finish the Turtle class from the previous page.
Filename Unit2\Lab18\Driver18.java. Test your Turtle class with the driver shown above. Then modify the
driver to draw a more interesting picture with your built-from-scratch turtles.
Test Data
Go to www.tjhsst.edu/compsci.
Two-45
Java
Unit2
Exercises
Lab18
Write the methods drawLine, drawCircle, and drawOval using only the BufferedImage method setRGB.
public void drawLine(BufferedImage img, int x1, int y1, int x2, int y2)
{
Two-46
Java
Unit2
Lab19
Array of Polkadots
Objective
Multiple polkadots in arrays.
Background
Here is declaration of a Polkadot reference:
Here is the instantiation of the Polkadot object using the 4-arg constructor:
As you know, Polkadot objects know how to draw themselves. You will have to have each polkadot draw itself
in the panel's Listener method.
The panel will also need a new collide method, something with the header
This method will have to visit each polkadot and check to see if the distance between the ball and that polkadot is
less than the sum of their respective radii.
Specification
Copy all files from Lab12. Modify PrizePanel to make an array of 50 (or 100, or 1000) polkadots. As before,
when the ball hits a polkadot, the polkadot jumps to a new position.
Test Data
Go to www.tjhsst.edu/compsci.
Two-47
Java
Unit2
Lab20
Array of Prizes
Objective
Polkadots, balls, and arrays, all re-written.
Background Spot
At every step of the way, the author could have made int x, y, r
different design decisions, both large and small. For Color c
example, here is an alternative hierarchy: boolean intersect(Spot)
void drawme(Graphics)
Prize Pinball
void lightup() int dx, dy, rightEdge, leftEdge
void setbound(int, int)
void tick()
int littlerandom()
In this version, prizes change color (from red to yellow) when they are hit by the pinball.
In this version, pinballs don't bounce at the same speed. Instead, they bounce in the reverse direction at a different
speed--a new, small random number.
Specification
Write Spot.java, Prize.java, and Pinball.java to the specifications shown above.
Filename Unit2\Lab20\PrizePanel.java. Write the panel. The Listener code is given above.
Test Data
Go to www.tjhsst.edu/compsci.
Two-48