Drawing Rectangles

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
Historical topic: Java appletsModern web browsers do not run Java applets. The Applet API was deprecated for removal before Java 25 and was removed in Java 26. Treat applet examples on this page as historical object-oriented/GUI examples; for new desktop interfaces use Swing where appropriate or JavaFX/OpenJFX.

Answer:

drawOval( 100-50, 300-50, 2*50, 2*50 )

Of course the method would work if you did the arithmetic and put the results in the method call.

Drawing Rectangles

To draw a rectangle, use the drawRect() method of the Graphics object. This method looks like:

drawRect(int  x, int  y, int  width, int  height)

It draws the outline of a rectangle using the current pen color. The left and right edges of the rectangle are at x and x + width respectively. The top and bottom edges of the rectangle are at y and y + height respectively.

This method is also used to draw a square. This applet draws a rectangle around the entire drawing area, then puts another rectangle in the center.

import java.swing.JApplet;
import java.awt.*;

// assume that the drawing area is 150 by 150
public class SquareAndRectangle extends JApplet
{
  final int areaSide = 150 ;
  final int width = 100, height = 50;

  public void paint ( Graphics gr )
  { 
    setBackground( Color.green );
    gr.setColor( Color.blue );

    // outline the drawing area
    gr.drawRect( 0, 0, areaSide-1, areaSide-1 ); 

    // draw interior rectangle.
    gr.drawRect( areaSide/2 - width/2 , 
        areaSide/2 - height/2, width, height ); 
   }
}

Here is what it draws on your screen:

Embedded Java applet removed: modern browsers do not support Java applets. The surrounding source code is retained for historical study.

In drawing the outer square, the value 1 was subtracted from its width and height so that the edges would be inside the drawing area.

QUESTION 16:

What do you suppose the following method does?

setColor( Color.blue )