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