1 /* 2 * A variant of program Number1. 3 * Program to pain a rectangle, centered in the cavas, made up of randomly 4 * colored, black framed squares with a white background. 5 */ 6 7 package npw; 8 9 import java.awt.Color; 10 import java.util.Random; 11 import java.util.Scanner; 12 import javax.swing.JOptionPane; 13 import javax.swing.SwingUtilities; 14 15 import painter.SPainter; 16 import shapes.SSquare; 17 18 public class Number2 { 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 2", 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 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, int nrOfRows, int nrOfColumns) { 42 // Position the painter to paint the rectangle of squares. 43 miro.mlt(((nrOfColumns - 1) / 2.0) * square.side()); 44 miro.mbk(((nrOfRows - 1) / 2.0) * square.side()); 45 //Paint the rectangle of squares. 46 int i = 1; 47 while (i <= nrOfRows) { 48 paintOneRow(miro, nrOfColumns, square); 49 miro.mfd(square.side()); 50 i = i + 1; 51 } 52 //Make the method invariant with respect to painter position. 53 miro.mrt(((nrOfColumns - 1) / 2.0) * square.side()); 54 miro.mfd(((nrOfRows - 1) / 2.0) * square.side()); 55 } 56 57 private static void paintOneRow(SPainter miro, int nrOfColumns, SSquare square) { 58 int i = 1; 59 while (i <= nrOfColumns) { 60 paintOneSquare(miro, square); 61 miro.mrt(square.side()); 62 i = i + 1; 63 } 64 miro.mlt(nrOfColumns * square.side()); 65 } 66 67 private static void paintOneSquare(SPainter miro, SSquare square) { 68 square.s2(); 69 miro.setColor(randomColor()); 70 miro.paint(square); 71 miro.setColor(Color.BLACK); 72 miro.draw(square); 73 square.x2(); 74 75 } 76 77 private static Color randomColor() { 78 Random rgen = new Random(); 79 int r = rgen.nextInt(256); 80 int g = rgen.nextInt(256); 81 int b = rgen.nextInt(256); 82 return new Color(r, b, g); 83 } 84 85 public Number2(){ 86 paintTheImage(); 87 } 88 89 public static void main(String[] args){ 90 SwingUtilities.invokeLater(new Runnable() { 91 @Override 92 public void run() { 93 new Number2(); 94 } 95 }); 96 97 } 98 } 99