PlotContext.java
/**
A rudimentary 'printer plotting' class for <code>Shape</code> objects.
@author Walt Leipold
*/
public class PlotContext
{
/**
Construct a <code>PlotContext</code> with a specified size.
@param cols number of columns in image
@param rows number of rows in image
*/
public PlotContext(int cols,int rows)
{
// Silently change unusable arguments to defaults.
if (rows <= 0)
rows = 22;
if (cols <= 0)
cols = 72;
this.rows = rows;
this.cols = cols;
screen = new char[rows][cols];
for (int j=0; j<cols; j++)
for (int i=0; i<rows; i++)
screen[i][j] = ' ';
}
/**
Construct a <code>PlotContext</code> with a default size.
*/
public PlotContext()
{
this(22,72);
}
/**
Write a character at a specified point on the plot.
@param x x-coordinate of point to plot
@param y y-coordinate of point to plot
@param c character to draw at (<code>x</code>,<code>y</code>)
*/
public void setPoint(int x,int y,char c)
{
if (x < 0 || x >= cols || y < 0 || y >= rows)
return;
screen[y][x] = c;
}
/**
Write a character at a specified point on the plot.
@param x x-coordinate of point to plot
@param y y-coordinate of point to plot
@param c character to draw at (<code>x</code>,<code>y</code>)
*/
public void setPoint(double x,double y,char c)
{
setPoint((int)Math.round(x),(int)Math.round(y),c);
}
/**
Displays the 'plot' constructed in this <code>PlotContext</code>.
@return a printable representation of the <code>PlotContext</code>
*/
public String toString()
{
int i,j;
StringBuffer b = new StringBuffer();
// Print the top of the frame.
b.append('+');
for (j=0; j<cols; j++)
b.append('-');
b.append('+');
b.append('\n');
// Print each line of the image.
for (i=0; i<rows; i++) {
b.append('|');
for (j=0; j<cols; j++)
b.append(screen[i][j]);
b.append('|');
b.append('\n');
}
// Print the top of the frame.
b.append('+');
for (j=0; j<cols; j++)
b.append('-');
b.append('+');
return b.toString();
}
private int rows,cols;
private char screen[][];
}