Overview | Schedule | Announcements | Resources | Assignments | Home |
As you will see, the problem of producing graphics on a computer screen is complex enough that one cannot usually keep all the details in mind at one time. An approach for managing these details is to break a large problem into smaller more easily solved problems, or sub-problems, and then put the solutions of the sub-problems together in a meaningful way. The laboratories in this unit will give you opportunities to experience some problem solving techniques and at the same time learn enough about graphics and programming in Java to be able to implement a non-trivial animated graphics computer application.
Since a triangle is a polygon with three vertices and a diamond is a polygon with four vertices, knowing how to create a triangle should help us understand how to create a diamond. So the approach we use is to make a copy of the Triangle class, rename it as a Diamond class and modify it to draw a diamond instead of a triangle.
First make a copy of the Triangle class:
Next, in the Diamond class, replace all occurrences of the word Triangle with the word Diamond (there are only two). It would also be a good idea to replace all occurrences of the word triangle with the word diamond (there are fourteen).
The last step is to modify the draw() method so that a diamond is displayed rather than a triangle. Below are the Java statements used by the draw method of the Triangle class to display a triangle in the active window. Note that a check is first made to see if the triangle object should be drawn at all, that is, draw the triangle only if its isVisible property is true. Next note how the x and y coordinates in the lines myPoly.addPoint correspond with the labeled points in the picture of the triangle below.
/* * Draw the triangle with current specifications on screen. */ private void draw() { if (isVisible) { Polygon myPoly = new Polygon(); //Points in order drawn: myPoly.addPoint(xPosition,yPosition); //First myPoly.addPoint(xPosition + (width/2),yPosition + height); //Second myPoly.addPoint(xPosition - (width/2),yPosition + height); //Third Canvas canvas = Canvas.getCanvas(); canvas.draw(this, color, myPoly); canvas.wait(10); } }
To display a diamond, simply determine the coordinates of the bottom vertex in the diamond shaped figure below and where it should appear in the drawing order. Then insert that point in the proper spot using a myPoly.addPoint statement. Note that height in the diagram below is different than a triangle height, so you will also need to modify the coordinates in two of the other myPoly.addPoint statements.
Test your Diamond class by creating some diamond objects and displaying them. Do the other methods in the Diamond class work too?
Overview | Schedule | Announcements | Resources | Assignments | Home |
DePauw University, Computer Science
Department, Spring 2005
Maintained by Brian
Howard (bhoward@depauw.edu
).
Last updated