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 import painter.SPainter; 9 import shapes.SSquare; 10 11 public class Number1 { 12 // The solution to the graphical problem. 13 private void paintTheImage() { 14 // Get the input information from the user. 15 int nrOfRows = getNumber("rows"); 16 int nrOfColumns = getNumber("columns"); 17 int sizeOfSquare = getNumber("square side length"); 18 19 // Establish the painter. 20 int height = nrOfRows * sizeOfSquare; 21 int width = nrOfColumns * sizeOfSquare; 22 SPainter miro = new SPainter("Number 1",width+50,height+50); 23 miro.setBrushWidth(4); 24 SSquare square = new SSquare(sizeOfSquare); 25 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 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 = i + 1; 48 } 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 static void paintOneRow(SPainter miro, int nrOfColumns, SSquare square) { 56 int i = 1; 57 while ( i <= nrOfColumns ) { 58 paintOneSquare(miro,square); 59 miro.mrt(square.side()); 60 i = i + 1; 61 } 62 miro.mlt(nrOfColumns*square.side()); 63 } 64 65 private static void paintOneSquare(SPainter miro, SSquare square) { 66 miro.setColor(randomColor()); 67 miro.paint(square); 68 miro.setColor(Color.BLACK); 69 miro.draw(square); 70 } 71 private static Color randomColor() { 72 Random rgen = new Random(); 73 int r = rgen.nextInt(256); 74 int g = rgen.nextInt(256); 75 int b = rgen.nextInt(256); 76 return new Color(r,b,g); 77 } 78 79 public Number1(){ 80 paintTheImage(); 81 } 82 83 public static void main(String[] args){ 84 SwingUtilities.invokeLater(new Runnable() { 85 @Override 86 public void run() { 87 new Number1(); 88 } 89 }); 90 } 91 }