1 package assign_4; 2 3 import painter.SPainter; 4 import shapes.SCircle; 5 import javax.swing.*; 6 import java.awt.*; 7 import java.util.Random; 8 import java.util.Scanner; 9 10 public class HirstDots { 11 public static void main(String[] args) { 12 SwingUtilities.invokeLater(new Runnable() { 13 @Override 14 public void run() { 15 new HirstDots(); 16 } 17 }); 18 } 19 20 public HirstDots() { 21 paintTheImage(); 22 } 23 24 private void paintTheImage() { 25 //Grab the input information 26 int width = getNumber("width"); 27 int height = getNumber("height"); 28 int colWidth = getNumber("dot spacing"); 29 //Establish the painter 30 SPainter painter = new SPainter("Hirst Dots", width, height); 31 SCircle dot = new SCircle(5); 32 //Move the painter to the upper left corner to get ready to paint the gradient 33 painter.mfd(height / 2); 34 painter.tl(90); 35 painter.mfd(width / 2 - 10); 36 painter.tl(90); 37 //Paint it! 38 paintGradient(painter, dot, height, width, colWidth); 39 } 40 41 private static int getNumber(String prompt) { 42 String nss = JOptionPane.showInputDialog(null, prompt + "?"); 43 Scanner scanner = new Scanner(nss); 44 return scanner.nextInt(); 45 } 46 47 private void paintGradient(SPainter painter, SCircle dot, int height, int width, int colWidth) { 48 int cols = 0; 49 //Calculate the number of columns. We want to fill the screen, but we don't want 50 //any dots only half on the canvas, so we subtract some space 51 int nrOfCols = (width / colWidth) - 2; 52 while (cols < nrOfCols) { 53 nextCol(painter, colWidth); 54 paintColumn(painter, dot, height, colWidth); 55 cols = cols + 1; 56 } 57 } 58 59 public void paintOneDot(SPainter painter, SCircle dot) { 60 randomColor(painter); 61 painter.paint(dot); 62 } 63 64 public void randomColor(SPainter painter) { 65 Random randomGenerator = new Random(); 66 int red = randomGenerator.nextInt(255); 67 int blue = randomGenerator.nextInt(255); 68 int green = randomGenerator.nextInt(255); 69 Color randomColor = new Color(red, green, blue); 70 painter.setColor(randomColor); 71 } 72 73 //Dots are spaced tighter together near the bottom of the canvas 74 private void paintColumn(SPainter painter, SCircle dot, int height, int colWidth) { 75 int travel = 0; 76 int totalDistanceTraveled = 0; 77 //Paint a row with decreasing distance between dots 78 while (totalDistanceTraveled < height - (dot.radius() * 3)) { 79 travel = colWidth; 80 totalDistanceTraveled = totalDistanceTraveled + travel; 81 painter.mfd(travel); 82 paintOneDot(painter, dot); 83 } 84 //Make the method invariant with respect to painter position 85 painter.mbk(totalDistanceTraveled); 86 } 87 88 //Moves the painter to the next column 89 private void nextCol(SPainter painter, int colWidth) { 90 painter.tl(90); 91 painter.mfd(colWidth); 92 painter.tr(90); 93 } 94 95 private int randomDistance(int maxDistance) { 96 Random rgen = new Random(); 97 return rgen.nextInt(maxDistance); 98 } 99 } 100