Graphic Java

Another method in the Graphics class is polyLine. Called like this:

  g.polyLine(x,y,l);
where x is an array of integer values representing the x-coordinates of the corners in the polyLine, y is an array of integer values representing the y-coordinates of the corners in the polyLine, and l is simply the number of corners in the polyLine.

The student must know how to declare and use arrays in order to use the polyLine method. An array is declared like this:

  int x[] = new int [5];
This line declares an array of five integer values.

The student must also know how to assign values to elements in the array. One thing that the student must first realize, in order to do this, is that the first element in an array has an address of zero. So, to assign a value to the third element in an array the student must write:

  x[2]=20;
This line assigns the value of 20 to the third element in an array named x.

So, once the student has two array defined like this:

  int x[]=new int[3];
  int y[]=new int[3];
and values assigned like this:
  x[0]=5;
  x[1]=10;
  x[2]=20;
  y[0]=40;
  y[1]=60;
  y[2]=80;
The polyLine method can be called like this:
  g.drawPolyline(x,y,x.length);
The number three could have been substituted for x.length, but it is better to use the length variable since it will work no matter what the length of x happens to be.
EXAMPLE: The student will create an applet like the one shown here. This activity provides the student with an introdution to polylines.
x

ASSIGNMENT:
In order to create the applet shown on this page the student will need to follow these diretions:

STEP ONE: The first two lines after the class definition will be:

  int x[]=new int[5];
  int y[]=new int[5];
This declares two arrays of integers.

STEP TWO: Add this method between the end of the init method and the beginning of the paint method:

  public void drawSQRT(Graphics g, int a, int b, int n){
    x[0]=a;  y[0]=b;
    x[1]=a+3;  y[1]=b;
    x[2]=a+6;  y[2]=b+4;
    x[3]=a+9;  y[3]=b-7;
    x[4]=a+25;  y[4]=b-7;
    g.drawPolyline(x,y,x.length);
    g.drawString(""+n+ " ="+(int)(Math.sqrt(n)), a+11, b+4);
  }
This method draws the square root symbol and it places the numbers and equal sign. The call to Math.sqrt simply returns the square root of the number fed to it.

STEP THREE: Call the drawSQRT method like this:

    drawSQRT(g, 30, 130, 81);
The g is the graphics object. The 30 is the x position to begin drawing at. The 130 is the y position to begin drawing at. The 81 is the number which is displayed and for which the square root is found.