Java Reference
In-Depth Information
ments for the coordinates, color and determining whether the shape is filled. The no-argument
constructor should, in addition to setting the default values, set the shape to be an unfilled shape.
You can draw lines, rectangles and ovals if you know two points in space. Lines require x1 , y1 ,
x2 and y2 coordinates. The drawLine method of the Graphics class will connect the two points
supplied with a line. If you have the same four coordinate values ( x1 , y1 , x2 and y2 ) for ovals and
rectangles, you can calculate the four arguments needed to draw them. Each requires an upper-left
x -coordinate value (the smaller of the two x -coordinate values), an upper-left y -coordinate value
(the smaller of the two y -coordinate values), a width (the absolute value of the difference between
the two x -coordinate values) and a height (the absolute value of the difference between the two y -
coordinate values). Rectangles and ovals should also have a filled flag that determines whether to
draw the shape as a filled shape.
There should be no MyLine , MyOval or MyRectangle variables in the program—only MyShape
variables that contain references to MyLine , MyOval and MyRectangle objects. The program should
generate random shapes and store them in an array of type MyShape . Method paintComponent
should walk through the MyShape array and draw every shape, by polymorphically calling every
shape's draw method.
Allow the user to specify (via an input dialog) the number of shapes to generate. The program
will then generate and display the shapes along with a status bar that informs the user how many of
each shape were created.
10.2 (Drawing Application Modification) In the preceding exercise, you created a MyShape hierar-
chy in which classes MyLine , MyOval and MyRectangle extend MyShape directly. If your hierarchy was
properly designed, you should be able to see the similarities between the MyOval and MyRectangle class-
es. Redesign and reimplement the code for the MyOval and MyRectangle classes to “factor out” the
common features into the abstract class MyBoundedShape to produce the hierarchy in Fig. 10.18.
Class MyBoundedShape should declare two constructors that mimic those of class MyShape , only
with an added parameter to specify whether the shape is filled. Class MyBoundedShape should also
declare get and set methods for manipulating the filled flag and methods that calculate the upper-
left x- coordinate, upper-left y -coordinate, width and height. Remember, the values needed to draw
an oval or a rectangle can be calculated from two (x, y) coordinates. If designed properly, the new
MyOval and MyRectangle classes should each have two constructors and a draw method.
java.lang.Object
MyShape
MyLine
MyBoundedShape
MyOval
MyRectangle
Fig. 10.18 | MyShape hierarchy with MyBoundedShape .
 
Search WWH ::




Custom Search