CPSC 170A
Program 2: Inheritance and GUIs
Due Tuesday, Feb 26, 2002
Problem Description
Write an applet that lets the user draw a square or circle and
change its color as follows:
- The applet should have two buttons that draw -- one should say "Draw
Square" and the other should say "Draw Circle".
When the user presses the "Draw Square" button, a square should be
drawn on the applet. When the user presses the "Draw Circle" button,
a circle should be drawn on the applet. In either case, the area of the
shape should be displayed below it.
- The applet should have three or more additional buttons
labeled with colors. When the user
presses one of these buttons, the square or circle should change to the
color on the button. The background colors of these buttons should match
the color that will be drawn.
When the "Draw Circle" or "Draw Square" button is pressed,
the shape drawn can be any color (black is fine). The color buttons can
then be used to change its color.
But if you get everything else working, think about how to make a new
shape whatever
color the last shape was (if there was a last shape). This is what the
demo does. Depending on how you go about this, you may need to define a
new variable and/or method to make this work.
Check out the demo to get a feel for this
functionality.
Approach
You must follow these guidelines in writing your applet:
- Write a Shape class that keeps information that would be of
interest to both a square and a circle -- its location, size, and color.
These values should be passed to the constructor. You will also
need a method to set the color.
Also provide two abstract methods, one to draw the shape and one to
return its area.
- Write two subclasses of Shape, Circle and Square. Think about
what variables and/or methods they will need.
- In your applet, declare a Shape instance variable. The paint
method should just draw this Shape. (Note that it's perfectly ok
to draw directly on the applet, even if it is holding GUI objects.)
You should
NOT declare
any Circle or Square variables.
- When the user presses the "Draw Circle" button, create a Circle object
and put it in the Shape variable, then repaint. When the user
presses the "Draw Square" button, do the same for a Square object.
- When the user presses a color button, just set the color property of
the shape being drawn and repaint.
To distinguish among the actions of the various buttons, you may either set
their actionCommands or write separate (inner) classes, each with its own
actionPerformed method. We discussed both of these methods in class.
Note that you will have a total of five separate files for this project:
- Shape.java -- the abstract Shape class
- Circle.java -- the Circle class, a subclass of Shape
- Square.java -- the Square class, a subclass of Shape
- DrawShapes.java -- the applet that holds the buttons and draws the shapes
- DrawShapes.html -- the html file used to view the applet