1 /* 2 * A program to paint an abstract gradient in the vertical direction. 3 */ 4 5 package npw; 6 7 import painter.SPainter; 8 import shapes.SCircle; 9 10 import javax.swing.*; 11 import java.awt.*; 12 import java.util.Random; 13 import java.util.Scanner; 14 15 import static javax.swing.SwingUtilities.invokeLater; 16 17 public class HirstDots { 18 private int spacingFactor = getNumber(" Dot Spacing"); 19 private int width = getNumber("Canvas Width in Pixels"); 20 private int height = getNumber("Canvas Height in Pixels "); 21 22 private HirstDots() { 23 paintTheImage(); 24 } 25 26 public static void main(String[] args) { 27 invokeLater( HirstDots::new ); 28 } 29 30 private void paintTheImage(){ 31 // Establish the painter 32 SPainter painter = new SPainter("SimpleDots", width, height); 33 SCircle dot = new SCircle(5); 34 // Move the painter to the upper left corner to get ready to paint the gradient 35 painter.mfd(height/2); 36 painter.tl(90); 37 painter.mfd(width/2 - 10); 38 painter.tl(90); 39 // Paint it! 40 paintGradient(painter, dot, height, width, spacingFactor); 41 } 42 43 private static int getNumber(String prompt) { 44 String nss = JOptionPane.showInputDialog(null,prompt+"?"); 45 Scanner scanner = new Scanner(nss); 46 return scanner.nextInt(); 47 } 48 49 // Supports double precision floating point numbers as spacingFactor values 50 private void paintGradient(SPainter painter, SCircle dot, int height, int width, int verticalSpacing){ 51 // Calculate the number of columns. We want to fill the screen, but we don't want 52 // any dots only half on the canvas, so we subtract some space. 53 int nrOfCols = ( width / verticalSpacing ) - 2; 54 int columnCount = 0; 55 while (columnCount < nrOfCols){ 56 nextCol(painter, verticalSpacing); 57 columnCount = columnCount + 1; 58 paintColumn(painter, dot, height); 59 } 60 } 61 62 private void paintOneDot(SPainter painter, SCircle dot){ 63 painter.setColor(randomColor()); 64 painter.paint(dot); 65 } 66 67 private void paintColumn(SPainter painter, SCircle dot, int height) { 68 int horizontalSpacing = spacingFactor; 69 int displacement = 0; 70 71 while(displacement < height) { 72 displacement = displacement + horizontalSpacing; 73 painter.mfd(horizontalSpacing); 74 paintOneDot(painter, dot); 75 } 76 // Make the method invariant with respect to painter position. 77 painter.mbk(displacement); 78 } 79 // Moves the painter to the next column. 80 private void nextCol(SPainter painter, double colWidth){ 81 painter.tl(90); 82 painter.mfd(colWidth); 83 painter.tr(90); 84 } 85 private Color randomColor(){ 86 Random rgen = new Random(); 87 int r = rgen.nextInt(255); 88 int g = rgen.nextInt(255); 89 int b = rgen.nextInt(255); 90 return new Color(r,g,b); 91 } 92 } 93