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