Sams Teach Yourself C in 21 Days

(singke) #1
More Java Techniques 751

BD6


Drawing Shapes and Lines ............................................................................


The Java AWT has many classes that are used for creating both two-dimensional and
three-dimensional shapes. The classes for drawing shapes are found in the
java.awt.geom. package. Basically, there is a class for each type of shape:rectangle,
line,ellipse, and so on. The general procedure for creating and displaying such shapes
is as follows:


  1. Create a window (Frame) as was explained in the previous demonstration program.

  2. Create an instance of each type of shape you want to draw: lines, rectangles,
    ellipses, and so forth. Set the properties to provide the desired shape characteris-
    tics, such as location, size, and color.

  3. Create a class that is based on the Canvasclass. In this class create a paintmethod
    that contains the code to draw the shapes. The paintmethod is automatically
    called by the operating system when the screen display needs updating.

  4. Create an instance of the class defined in step 3 and place it on the frame created in
    step 1.
    You can see that the steps for creating the shapes are separate from the steps for display-
    ing them on the screen. I realize that this is a rather complex topic. Because I cannot go
    into the details at length, it is best to use a demonstration program. The code in Listing
    B6.4 creates a window and draws several simple shapes on it.


LISTINGB6.4 Drawing.java. Using the Java AWT to draw shapes onscreen
1: import java.awt.*;
2: import java.awt.geom.*;
3:
4: public class DrawingTest extends Frame {
5: Shape shapes[] = new Shape[4];
6: public DrawingTest (String title) {
7: super(title);
8: setSize(500, 400);

Within a subclass, you use the superkeyword to call methods belonging to
the superclass. Thus, the line super.SomeMethod();calls the method named
SomeMethodin the superclass. Using superby itself calls the superclass’s con-
structor. The only place you can do this is on the first line in the subclass’s
constructor. Note that the superclass’s constructor will automatically be
called from the subclass’s constructor, but by using superyou can specify the
arguments to be passed.

Note


41 448201x-Bonus6 8/13/02 11:23 AM Page 751

Free download pdf