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