INTRODUCTION TO COMPUTER SCIENCE
Robert Sedgewick and Kevin Wayne


This is the syntax highlighted version of Voronoi.java.

/*************************************************************************
 *  Compilation:  javac Voronoi.java
 *  Execution:    java Voronoi
 *  Dependencies: InteractiveDraw.java DrawListener.java
 * 
 *  Plots the points that the user clicks, and draws the Voronoi diagram.
 *
 *  Limitations
 *  -----------
 *    - at most 1000 points.
 *
 *************************************************************************/

import java.awt.Color;

public class Voronoi implements DrawListener {
    private int SIZE = 512;
    private Point[][] nearest = new Point[SIZE][SIZE];  // which point is pixel (i, j) nearest?

    private InteractiveDraw d;


    public Voronoi() {
        d = new InteractiveDraw(SIZE, SIZE);
        d.setScale(0, 0, SIZE, SIZE);
        d.addListener(this);
        d.show();
    }

    public void mousePressed(double x, double y) {
        Point p = new Point(x, y);


        // compare each pixel (i, j) and find nearest point
        d.setColorRandom();
        for (int i = 0; i < SIZE; i++) {
            for (int j = 0; j < SIZE; j++) {
                Point q = new Point(i, j);
                if (q.distanceTo(p) < q.distanceTo(nearest[i][j])) {
                    nearest[i][j] = p;
                    d.go(i, j);
                    d.spot(0);
                }
            }
        }

        // draw the point afterwards
        d.setColor(Color.black);
        d.go(x, y);
        d.spot(4);

        d.show();
    }


    public void keyTyped(char c) { d.save("voronoi" + c + ".png"); }
    public void mouseDragged(double x, double y)  { }
    public void mouseReleased(double x, double y) { }


    // test client
    public static void main(String args[]) {
        Voronoi voronoi = new Voronoi();
    }
 
   
}


Last updated: Fri May 14 23:28:38 EDT 2004 .
Copyright © 2004, Robert Sedgewick and Kevin Wayne.