Methods

This code has a method to draw a heart.

import java.applet.Applet;
   import java.awt.*;
public class heartpatterns extends Applet
   {
   public void paint (Graphics g)
   {
   heart (25, 75, Color.pink);
   }
   public void heart (int x, int y, Color c)
   {
   Graphics g = getGraphics ();
   g.setColor (c);
   g.fillOval (x, y, 10, 10);
   g.fillOval (x + 8, y, 10, 10);
   int xArray [] = {x, x + 8, x + 18};
   int yArray [] = {y + 6, y + 15, y + 6};
   g.fillPolygon (xArray, yArray, 3);
   }
   }
 

Write down the answers to the following questions.

  1. What is the name of the class?
  2. What is the name of both methods in the class?
  3. Run it. What does it draw on the screen?
  4. This is how the heart method is called: heart (25, 75, Color.pink);
  5. What co-ordinate is the heart drawn at? (heart (25, 75, Color.pink);)
  6. What colour is it drawn in? (heart (25, 75, Color.pink);)
  7. How would you draw a heart that was yellow in position 180, 34?

In the heart method:

  1. Suppose that x was 20 and y was 10. What actual numbers would be calculated in the following lines:

    g.fillOval (x, y, 10, 10);

    g.fillOval (x + 8, y, 10, 10);

    int xArray [] = {x, x + 8, x + 18};

  2. int yArray [] = {y + 6, y + 15, y + 6};

  3. Suppose that x was 180 and y was 34. What actual numbers would be calculated in the following lines:

    g.fillOval (x, y, 10, 10);

    g.fillOval (x + 8, y, 10, 10);

    int xArray [] = {x, x + 8, x + 18};

  4. int yArray [] = {y + 6, y + 15, y + 6};

  5. What do x, y, and c represent in the method line public void heart (int x, int y, Color c)?
  6. If you called heart(12, 23, Color.red), what values would x, y and c have?
  7. If you called heart (180, 34, Color.yellow), what values would x, y and c have

Code the following in Ready to Program.

Adapt the program in the following ways.

(A) Make a red heart, then a green one, then a blue one. All three should be on the screen at the same time. You will need to do this in paint.

(B) Change the paint method so it puts 25 hearts on the screen in a row.

   int x = 0;
   int y = 0;
   int i = 0;
 while (i < 25)
 {
   heart (x, y, Color.pink);
   x += 20;
   i++;
 }

(C) Make a loop that puts 25 hearts hearts in a row and then 25 rows of 25 hearts. (put a loop inside a loop). This should happen in the paint method.

   int x = 0;
   int y = 0;
   int i = 0;
   int j = 0;
   while (i < 50)
   {
     while (j < 50)
     {
        heart (x, y, Color.pink);
        x += 20;
        j++;
     }
   x = 0;
   y += 16;
   i++;
   j = 0;
   }