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