September 24, 2003

Drawing Stick Figures: Version 2 with a slider



/*
An applet that demonstrates the use of methods.

We will write a method, called drawPerson, that, given the x and y
coordinates of an anchor point, and a height in pixels, it draws
a stick figure anchored at that point.

In this, Version 2 of the applet, the stick figures sizes can be varied
by adjusting the value of the slider.
*/
import java.awt.*;
   import java.applet.Applet;
   import java.awt.event.*;
public class PersonApplet extends Applet implements AdjustmentListener 
{
   Scrollbar slider;
   Label sLabel;
   
   int height = 50;
   
   public void init() {
      // Create GUI
   
      // Create the label
      sLabel = new Label("Change Size:");
   
      // add the label
      add(sLabel);
   
      // Create the slider
      slider = new Scrollbar(Scrollbar.HORIZONTAL, 50, 1, 30, 350);
   
      // Add it to the applet
      add(slider);
     
      // Add a listener for it
      slider.addAdjustmentListener(this);
   
   } // init
   
   public void drawPerson(Graphics g, int x, int y, int h) {
      // draw a stick figure anchored at x, y of height h
   
      // Draw head
      g.fillOval(x-h/8, y-h, h/4, h/4);
   
      // Draw body
      g.drawLine(x, y-3*h/4, x, y-h/4);
   
      // Draw Legs
      g.drawLine(x, y-h/4, x-h/8, y);
       g.drawLine(x, y-h/4, x+h/8, y);
   
      // Draw arms
      g.drawLine(x, y-h/2, x-h/8, y-3*h/4);
      g.drawLine(x, y-h/2, x+h/8, y-3*h/4);
   } //
   
   
   public void paint(Graphics g) {
   
      g.setColor(Color.blue);
      drawPerson(g, 150, 380, height);
   
      g.setColor(Color.red);
      drawPerson(g, 50, 380, height*2);
   
      g.setColor(Color.green);
      drawPerson(g, 100, 380, height*3);
   
   } // paint
   
   // Listener method for the slider
   
   public void adjustmentValueChanged(AdjustmentEvent e) {
   
      height = slider.getValue();
   
      repaint();
   
   } // adjustmentValueChanged
   
   } // PersonApplet
 
Back to class exmaples | Back to CS110 Materials page