This program draws a stick figure where the user clicks. Whenever the user depresses the mouse, the word "Hi" appears where the mouse is. When the user moves the mouse out of the window, a stick figure is drawn in the upper left corner of the window.
import objectdraw.*;
import java.awt.*;
/**
* Draws a stick figure on the display. When the user depresses the mouse
* button, the stick figure says "hi"
*
* @author Barbara Lerner
* @version March 3, 2008
*/
public class DrawAStickFigure extends WindowController
{
/**
* Resize the window
*/
public void begin() {
resize (600, 600);
}
/**
* Draw a stick figure where the user clicks.
*/
public void onMouseClick (Location point) {
new StickFigure (point, canvas);
}
/**
* Draw a stick figure in the upper left corner of the window.
*/
public void onMouseExit (Location point) {
new StickFigure (new Location(0, 0), canvas);
}
/**
* Add the text "hi" to the screen when the user depresses the mouse
* button.
*/
public void onMousePress (Location point) {
new Text ("Hi!", point, canvas);
}
}
import objectdraw.*;
import java.awt.*;
/**
* Draws a stick figure
*
* @author Barbara Lerner
* @version October 9, 2008
*/
public class StickFigure
{
// The size of the head
private static final int HEAD_SIZE = 100;
// The size of the body
private static final int BODY_SIZE = HEAD_SIZE * 2;
// The relative location of the hand to the shoulder
private static final int ARM_X_OFFSET = HEAD_SIZE / 2;
private static final int ARM_Y_OFFSET = HEAD_SIZE / 2;
// The relative location of the foot from the shoulder
private static final int LEG_X_OFFSET = HEAD_SIZE / 2;
private static final int LEG_Y_OFFSET = LEG_X_OFFSET * 2;
/**
* Draws a stick figure
*
* @param upperLeft the upper left location for the stick figure
* @param figureCanvas the canvas to draw on
*/
public StickFigure (Location upperLeft, DrawingCanvas figureCanvas) {
// The location of the head
double headLeft = upperLeft.getX();
double headTop = upperLeft.getY();
// The location of the body
double bodyLeft = headLeft + (HEAD_SIZE / 2);
double bodyTop = headTop + HEAD_SIZE;
// The location of the arms
double armBottom = bodyTop + ARM_Y_OFFSET;
double armTop = bodyTop;
double leftArmLeft = bodyLeft - ARM_X_OFFSET;
double rightArmRight = bodyLeft + ARM_X_OFFSET;
// The location of the legs.
double legTop = bodyTop + BODY_SIZE;
double leftLegLeft = bodyLeft - LEG_X_OFFSET;
double rightLegRight = bodyLeft + LEG_X_OFFSET;
double legBottom = legTop + LEG_Y_OFFSET;
// Draw the head
new FramedOval (headLeft, headTop, HEAD_SIZE, HEAD_SIZE, figureCanvas);
// Draw the body
new Line (bodyLeft, bodyTop, bodyLeft, bodyTop + BODY_SIZE, figureCanvas);
// Draw the arms
new Line (leftArmLeft, armTop, bodyLeft, armBottom, figureCanvas);
new Line (rightArmRight, armTop, bodyLeft, armBottom, figureCanvas);
// Draw the legs
new Line (bodyLeft, legTop, leftLegLeft, legBottom, figureCanvas);
new Line (bodyLeft, legTop, rightLegRight, legBottom, figureCanvas);
}
}