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.SCircle; 11 import shapes.SSquare; 12 13 public class Number4 { 14 15 // The solution to the graphical problem. 16 private void paintTheImage() { 17 // Get the input information from the user. 18 int nrOfRows = getNumber("rows"); 19 int nrOfColumns = getNumber("columns"); 20 int sizeOfCircle = getNumber("circle radius"); 21 String color = getColor("red blue or green"); 22 23 24 // Establish the painter. 25 int height = nrOfRows * sizeOfCircle * 2; 26 int width = nrOfColumns * sizeOfCircle * 2; 27 SPainter miro = new SPainter("Number 4",width+50,height+50); 28 miro.setBrushWidth(4); 29 SCircle circle = new SCircle(sizeOfCircle); 30 // Paint the rectangles. 31 paintRectangle(miro,circle,nrOfRows,nrOfColumns,color); 32 } 33 34 private String getColor(String prompt) { 35 String nss = JOptionPane.showInputDialog(null,prompt+"?"); 36 Scanner scanner = new Scanner(nss); 37 return scanner.nextLine(); 38 } 39 40 private static int getNumber(String prompt) { 41 String nss = JOptionPane.showInputDialog(null,prompt+"?"); 42 Scanner scanner = new Scanner(nss); 43 return scanner.nextInt(); 44 } 45 46 private static void paintRectangle(SPainter miro, SCircle circle, 47 int nrOfRows, int nrOfColumns,String color) { 48 // Position the painter to paint the rectangle of squares. 49 miro.mlt(((nrOfColumns-1)/2.0) * circle.diameter()); 50 miro.mbk(((nrOfRows-1)/2.0) * circle.diameter()); 51 // Paint the rectangle of squares. 52 int i = 1; 53 while ( i <= nrOfRows) { 54 paintOneRow(miro,nrOfColumns,circle, color); 55 miro.mfd(circle.diameter()); 56 i = i + 1; 57 } 58 // Make the method invariant with respect to painter position. 59 miro.mrt(((nrOfColumns-1)/2.0) * circle.diameter()); 60 miro.mfd(((nrOfRows-1)/2.0) * circle.diameter()); 61 } 62 63 private static void paintOneRow(SPainter miro, int nrOfColumns, SCircle circle, String color) { 64 int i = 1; 65 while ( i <= nrOfColumns ) { 66 paintOneSquare(miro,circle,color); 67 miro.mrt(circle.diameter()); 68 i = i + 1; 69 } 70 miro.mlt(nrOfColumns*circle.diameter()); 71 } 72 73 private static void paintOneSquare(SPainter miro, SCircle circle, String color) { 74 //Add two instructions 75 circle.s2(); 76 if (color.equalsIgnoreCase("red")) { 77 miro.setColor(Color.RED); 78 miro.paint(circle); 79 } else if (color.equalsIgnoreCase("blue")) { 80 miro.setColor(Color.BLUE); 81 miro.paint(circle); 82 } else if (color.equalsIgnoreCase("green")) { 83 miro.setColor(Color.green); 84 miro.paint(circle); 85 } else { 86 miro.setColor(Color.black); 87 miro.paint(circle); 88 } 89 circle.x2(); 90 } 91 92 public Number4(){ 93 paintTheImage(); 94 } 95 96 public static void main(String[] args){ 97 SwingUtilities.invokeLater(new Runnable() { 98 @Override 99 public void run() { 100 new Number4(); 101 } 102 }); 103 } 104 } 105