Example 1: Design and Write a Method

The signature for our method is:

public static void fillBoundedCircle(Graphics g, int centerX, int centerY, int diameter)

After the signature of a method comes the block of code that is executed when the method is called. This is the body of the method.

Before we can write the body of the method, we need to design the method by determining the algorithm it should use.

The algorithm for this method is:

  1. Determine the bounding rectangle for the circle.

  2. Draw the circle using this rectangle's top left x and y coordinates and the passed-in diameter.

  3. Draw the bounding rectangle in red.

Did you notice that the first step is referring to a second method? Before reading the details below, let's design the signature for a method called calcBoundRect().

Because we have this method, the method to actually draw the circle is fairly short and easy to follow.

Code for the fillBoundedCircle() Method

/**
 *  Draws the specified filled-in circle using the current color and
 *  displays the bounding rectangle in red.
 */

public void fillBoundedCircle(Graphics g, int centerX, int centerY,
		int diameter)
{
	int	topX, topY;

	// 1. Determine the bounding rectangle for the circle.

	Rectangle r = calcBoundRect(centerX, centerY, diameter);

	/*
	 * 2. Draw the circle using this rectangle's top left x and y
	 *    coordinates and the passed-in diameter.
	 */

	topX = (int)r.getX();
	topY = (int)r.getY();

	g.fillOval(topX, topY, diameter, diameter);

	// 3. Draw the bounding rectangle in red.

	g.setColor(Color.red);
	g.drawRect(topX, topY, diameter, diameter);
}

Notice the javadoc comment right before the method's signature. This will show up as the description of the method when the javadoc command is run. You can have a single sentence (a sentence ends in a period). It should be a brief explanation - don't repeat information that can be determined by reading the signature.

Now let's write the code for our calcBoundRect()method.