1 /* 2 * Program to paint a rectangle, centered in the canvas, made up of randomly 3 * colored, spaced circles. The user inputs the number of rows and columns. 4 */ 5 6 package npw; 7 8 import java.awt.Color; 9 import java.util.Scanner; 10 import javax.swing.JOptionPane; 11 import javax.swing.SwingUtilities; 12 13 import painter.SPainter; 14 import shapes.SCircle; 15 16 public class Number4 { 17 // The solution to the graphical problem. 18 private void paintTheImage() { 19 // Get the input information fron the user. 20 int nrOfRows = getNumber("rows"); 21 int nrOfColumns = getNumber("columns"); 22 int radius = getNumber("radius"); 23 // Establish the painter. 24 int height = nrOfRows * 2 * radius; 25 int width = nrOfColumns * 2 * radius; 26 SPainter miro = new SPainter("Number 4",width+50,height+50); 27 miro.setBrushWidth(4); 28 SCircle circle = new SCircle(radius); 29 String command = JOptionPane.showInputDialog(null, "pick blue, red, or green dots"); 30 if (command == null) { 31 command = "exit"; 32 } // user clicked on Cancel 33 if (command.equalsIgnoreCase("blue")) { 34 miro.setColor(Color.BLUE); 35 } else if (command.equalsIgnoreCase("red")) { 36 miro.setColor(Color.RED); 37 } else if (command.equalsIgnoreCase("green")) { 38 miro.setColor(Color.GREEN); 39 } else { 40 miro.setColor(Color.BLACK); 41 } 42 // Paint the rectangles. 43 paintRectangle(miro,circle,nrOfRows,nrOfColumns); 44 } 45 46 private static int getNumber(String prompt) { 47 String nss = JOptionPane.showInputDialog(null,prompt+"?"); 48 Scanner scanner = new Scanner(nss); 49 return scanner.nextInt(); 50 } 51 52 private static void paintRectangle(SPainter miro, SCircle circle, 53 int nrOfRows, int nrOfColumns) { 54 // Position the painter to paint the rectangle of squares. 55 miro.mlt(((nrOfColumns-1)/2.0) * circle.diameter()); 56 miro.mbk(((nrOfRows-1)/2.0) * circle.diameter()); 57 // Paint the rectangle of squares. 58 int i = 1; 59 while ( i <= nrOfRows) { 60 paintOneRow(miro,nrOfColumns,circle); 61 miro.mfd(circle.diameter()); 62 i = i + 1; 63 } 64 // Make the method invariant with respect to painter position. 65 miro.mrt(((nrOfColumns-1)/2.0) * circle.diameter()); 66 miro.mfd(((nrOfRows-1)/2.0) * circle.diameter()); 67 } 68 69 private static void paintOneRow(SPainter miro, int nrOfColumns, SCircle circle) { 70 int i = 1; 71 while ( i <= nrOfColumns ) { 72 paintOneCircle(miro,circle); 73 miro.mrt(circle.diameter()); 74 i = i + 1; 75 } 76 miro.mlt(nrOfColumns*circle.diameter()); 77 } 78 79 private static void paintOneCircle(SPainter miro, SCircle circle) { 80 circle.s2(); 81 miro.paint(circle); 82 circle.x2(); 83 } 84 85 public Number4(){ 86 paintTheImage(); 87 } 88 89 public static void main(String[] args){ 90 SwingUtilities.invokeLater(new Runnable() { 91 @Override 92 public void run() { 93 new Number4(); 94 } 95 }); 96 } 97 }