teaching machines

CS 145 Lecture 25 – Shape Plotter

May 4, 2012 by . Filed under cs145, lectures, spring 2012.

Agenda

Program This

You have:

How do you draw the polygon?

Code

Point.java

package prefinal;

public class Point {

  private int x;
  private int y;
  
  public Point(int x,
               int y) {
    this.x = x;
    this.y = y;
  }

  public int getX() {
    return x;
  }

  public int getY() {
    return y;
  }
}

ZaboomafuCanvas.java

package prefinal;

import java.awt.Graphics;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ZaboomafuCanvas extends JPanel {

  private GrowablePointArray points;

  public ZaboomafuCanvas(GrowablePointArray points) {
    this.points = points;
  }

  protected void paintComponent(Graphics g) {
    for (int i = 0; i < points.size() - 1; ++i) {
      drawLineBetween(g, points.get(i), points.get(i + 1));
    }
    drawLineBetween(g, points.get(0), points.get(points.size() - 1));
  }

  private void drawLineBetween(Graphics g,
                               Point a,
                               Point b) {
    g.drawLine(a.getX(), a.getY(), b.getX(), b.getY());
  }

  public static void main(String[] args) throws FileNotFoundException {
    JFrame frame = new JFrame();

    // Point[] points = {
    // new Point(50, 100),
    // new Point(100, 100),
    // new Point(75, 0),
    // };

    Scanner in = new Scanner(new File("/home/user/rectangle.txt"));
//    int nPoints = 0;
//    Point[] points = new Point[
    GrowablePointArray points = new GrowablePointArray();
    
    while (in.hasNextInt()) {
      int x = in.nextInt();
      int y = in.nextInt();
      Point point = new Point(x, y);
//      points[nPoints] = point;
//      ++nPoints;
      points.add(point);
    }

    frame.add(new ZaboomafuCanvas(points));

    frame.setSize(200, 200);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }
}

Haiku

Hide that ugly stuff.
The less you see the better.
Bologna’s that way.