CSE142 Program Example Handout #23
Input file simplepic.dat
------------------------
150 100
RED 0 0 40 30
GREEN 40 0 110 30
BLACK 40 0 3 30
BLACK 0 30 150 3
YELLOW 0 33 52 77
BLUE 55 33 80 77
BLACK 52 33 3 77
BLACK 135 33 3 77
Program file RectanglePainter.java
----------------------------------
// Steve Gribble
// February 14, 2006
//
// This program will draw to a canvas according to the
// commands contained in the user-specified file.
import java.util.*;
import java.io.*;
import java.awt.*;
public class RectanglePainter {
public static void main(String[] args) throws FileNotFoundException {
String filename = getInputFile();
processFile(filename);
}
// Asks the user for a filename, and returns it
public static String getInputFile() {
Scanner console_in = new Scanner(System.in);
System.out.print("File name: " );
String filename = console_in.next();
System.out.println();
return filename;
}
// Processes the file, a line at a time
public static void processFile(String name) throws FileNotFoundException {
Scanner file_in = new Scanner(new File(name));
// Read in the first line, which specifies the canvas size
String firstline = file_in.nextLine();
// Pull out the x and y
Scanner textscan = new Scanner(firstline);
int x, y;
x = textscan.nextInt();
y = textscan.nextInt();
// Create the canvas
DrawingPanel p = new DrawingPanel(x, y);
p.setBackground(Color.WHITE);
Graphics g = p.getGraphics();
// Now process the drawing commands a line at a time
while (file_in.hasNextLine()) {
processLine(file_in.nextLine(), g);
}
}
// Processes a line of the file
public static void processLine(String text, Graphics g) {
Scanner textscan = new Scanner(text);
// split the line into the five tokens
String color;
int x, y, w, h;
color = textscan.next();
x = textscan.nextInt();
y = textscan.nextInt();
w = textscan.nextInt();
h = textscan.nextInt();
// set the paintbrush to the specified color
if (color.equals("BLACK")) {
g.setColor(Color.BLACK);
} else if (color.equals("RED")) {
g.setColor(Color.RED);
} else if (color.equals("GREEN")) {
g.setColor(Color.GREEN);
} else if (color.equals("BLUE")) {
g.setColor(Color.BLUE);
} else if (color.equals("YELLOW")) {
g.setColor(Color.YELLOW);
} else {
// make white be the default color
g.setColor(Color.WHITE);
}
// draw the rectangle
g.fillRect(x, y, w, h);
}
}