1 /* 2 * Program to paint a rectangle, centered in the canvas, made up of randomly colored, 3 * black-framed squares with whitespace between, above, and below each square 4 */ 5 6 package npw; 7 8 import painter.SPainter; 9 import shapes.SSquare; 10 import javax.swing.*; 11 import java.awt.*; 12 import java.util.Random; 13 import java.util.Scanner; 14 15 public class Number2 { 16 //The solution to the graphical problem 17 private void paintTheImage() { 18 //Get the input info from the user 19 int nrOfRows = getNumber("rows"); 20 int nrOfColumns = getNumber("columns"); 21 int sizeOfSquare = getNumber("square side length"); 22 //Establish the painter 23 int height = nrOfRows * sizeOfSquare; 24 int width = nrOfColumns * sizeOfSquare; 25 SPainter miro = new SPainter("Number 2", width+50, height+50); 26 miro.setBrushWidth(4); 27 SSquare square = new SSquare(sizeOfSquare); 28 //Paint the rectangles 29 paintRectangle(miro, square, nrOfRows, nrOfColumns); 30 } 31 32 private static int getNumber(String prompt) { 33 String nss = JOptionPane.showInputDialog(null, prompt+"?"); 34 Scanner scanner = new Scanner(nss); 35 return scanner.nextInt(); 36 } 37 38 private static void paintRectangle(SPainter miro, SSquare square, int nrOfRows, int nrOfColumns) { 39 //Position the painter to paint the rectangle of squares 40 miro.mlt(((nrOfColumns-1)/2.0) * square.side()); 41 miro.mbk(((nrOfRows-1)/2.0) * square.side()); 42 //Paint the rectangle of squares 43 int i = 1; 44 while(i <= nrOfRows) { 45 paintOneRow(miro, nrOfColumns, square); 46 miro.mfd(square.side()); 47 i++; 48 } 49 //Make the method invariant with respect to pointer position 50 miro.mrt(((nrOfColumns-1)/2.0) * square.side()); 51 miro.mfd(((nrOfRows-1)/2.0) * square.side()); 52 } 53 54 private static void paintOneRow(SPainter miro, int nrOfColumns, SSquare square) { 55 int i = 1; 56 while(i <= nrOfColumns) { 57 paintOneSquare(miro, square); 58 miro.mrt(square.side()); 59 i++; 60 } 61 miro.mlt(nrOfColumns*square.side()); 62 } 63 64 private static void paintOneSquare(SPainter miro, SSquare square) { 65 square.s2(); //make square smaller by half to show white space 66 miro.setColor(randomColor()); 67 miro.paint(square); 68 miro.setColor(Color.BLACK); 69 miro.draw(square); 70 square.x2(); //put square back to regular size so loop doesn't go cray 71 } 72 73 private static Color randomColor() { 74 Random rgen = new Random(); 75 int r = rgen.nextInt(256); 76 int g = rgen.nextInt(256); 77 int b = rgen.nextInt(256); 78 return new Color(r,b,g); 79 } 80 81 public Number2() { 82 paintTheImage(); 83 } 84 85 public static void main(String[] args) { 86 SwingUtilities.invokeLater(new Runnable() { 87 @Override 88 public void run() { 89 new Number2(); 90 } 91 }); 92 } 93 }