Java Reference
In-Depth Information
7
public static void main(String[] args)
8
{
9
DrawPanel panel = new DrawPanel();
10
JFrame app = new JFrame();
11
12
app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
13
app.add(panel);
14
app.setSize( 300 , 300 );
15
app.setVisible( true );
16
}
17
} // end class TestDraw
Fig. 8.19 | Creating a JFrame to display a DrawPanel . (Part 2 of 2.)
GUI and Graphics Case Study Exercise
8.1 Extend the program in Figs. 8.17-8.19 to randomly draw rectangles and ovals. Create classes
MyRectangle and MyOval . Both of these classes should include x1 , y1 , x2 , y2 coordinates, a color and a
boolean flag to determine whether the shape is filled. Declare a constructor in each class with argu-
ments for initializing all the instance variables. To help draw rectangles and ovals, each class should
provide methods getUpperLeftX , getUpperLeftY , getWidth and getHeight that calculate the upper-
left x -coordinate, upper-left y -coordinate, width and height, respectively. The upper-left x -coordinate
is the smaller of the two x -coordinate values, the upper-left y -coordinate is the smaller of the two y -
coordinate values, the width is the absolute value of the difference between the two x -coordinate val-
ues, and the height is the absolute value of the difference between the two y -coordinate values.
Class DrawPanel , which extends JPanel and handles the creation of the shapes, should declare
three arrays, one for each shape type. The length of each array should be a random number
between 1 and 5. The constructor of class DrawPanel will fill each array with shapes of random
position, size, color and fill.
In addition, modify all three shape classes to include the following:
a)
A constructor with no arguments that sets the shape's coordinates to 0 , the color of the
shape to Color.BLACK , and the filled property to false ( MyRectangle and MyOval only).
b)
Set methods for the instance variables in each class. The methods that set a coordinate
value should verify that the argument is greater than or equal to zero before setting the
coordinate—if it's not, they should set the coordinate to zero. The constructor should
call the set methods rather than initialize the local variables directly.
c)
Get methods for the instance variables in each class. Method draw should reference the
coordinates by the get methods rather than access them directly.
Search WWH ::




Custom Search